【问题标题】:Splitting one line of a Csv into multiple lines in PowerShell在 PowerShell 中将 Csv 的一行拆分为多行
【发布时间】:2015-07-08 09:40:17
【问题描述】:

我有一个看起来像这样的 Csv:

No,BundleNo,Grossweight,Pieces,Tareweight,Netweight
1,Q4021317/09,193700,1614,646,193054
2,Q4021386/07,206400,1720,688,205712

我首先需要做的是对 Netweight 列进行一些数学运算以获得两个值,$x$y。 然后我需要将 Csv 中的每一行拆分为 $x 数据行,其中每一行数据看起来像 "AL,$y"

在下面的示例中,我成功获取了每一行的 $x$y 的值。当尝试将每一行拆分为$x 行时,问题就来了...:

$fileContent = Import-Csv $File

$x = ( $fileContent | ForEach-Object { ( [System.Math]::Round( $_.Netweight /25000 ) ) } )
$y = ( $fileContent | ForEach-Object { $_.Netweight / ( [System.Math]::Round( $_.Netweight /25000 ) ) } )

$NumRows = ( $fileContent | ForEach-Object { (1..$x) } )
$rows = ( $NumRows | ForEach-Object { "Al,$y" } )

当 Csv 中有一行数据时,此代码可以正常工作。 IE。如果$x = 8 and $y = 20,它将返回8行数据,看起来像"AL,20"。 但是,当 Csv 中有多个行时,我会收到一条错误消息:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".

我希望我已经解释过了,如果有任何帮助,我们将不胜感激。 谢谢, 约翰

【问题讨论】:

  • $x = $fileContent | ForEach-Object { $_.Something } 将导致$x 是一个长度为$fileContent.Count 的数组,而不仅仅是一个整数

标签: csv powershell


【解决方案1】:

不要一遍又一遍地使用ForEach-Object,只需遍历csv一次并一次生成一个$x$y结果:

$fileContent = @'
No,BundleNo,Grossweight,Pieces,Tareweight,Netweight
1,Q4021317/09,193700,1614,646,193054
2,Q4021386/07,206400,1720,688,205712
'@ | ConvertFrom-Csv

foreach($line in $fileContent){
    $x = [System.Math]::Round( $line.Netweight / 25000 )
    if($x -ne 0){
        $y = $line.Netweight / $x
        1..$x |ForEach-Object {"AL,$y"}
    }
}

导致$x 每行"AL,$y" 字符串数:

AL,24131.75
AL,24131.75
AL,24131.75
AL,24131.75
AL,24131.75
AL,24131.75
AL,24131.75
AL,24131.75
AL,25714
AL,25714
AL,25714
AL,25714
AL,25714
AL,25714
AL,25714
AL,25714

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多