Import-csv和过滤psobjects

eni9jsuy  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(75)

我正在导入一个csv..我想过滤掉长度为$null/ zero(0)的行。我尝试这样做..

$csv = Import-Csv $path | Where-object{ ($_.PSObject.Properties | ForEach-Object {$_.length}) -eq 0}

但我没有得到预期的结果。
如果我在已知的测试错误csv行(第一行,第0行)上进行磨练,

$csv[0] | Select-Object 'Today Maximum Drawdown' 
($t.'Today Maximum Drawdown').length

我得到的长度为零(0)。
我错过了什么?

mgdq6dx1

mgdq6dx11#

如果你想跳过任何一行有一个“空单元格”,我会跳过你试图做一行的部分:

@'
A, B, C
1, 2, 3
1,  , 3
 , 2,
1, 2, 3
'@ | ConvertFrom-Csv | ForEach-Object { $properties = $null } {
    # for the first object to process
    if (-not $properties) {
        # get the properties (Columns of the CSV)
        $properties = $_.PSObject.Properties.Name
    }

    foreach ($property in $properties) {
        if ([string]::IsNullOrWhiteSpace($_.$property)) {
            return # skip this row
        }
    }
    # else, output it
    $_
}

如果你想用Where-Object来做,这会使它更难阅读,你可以使用Enumerable.Any

@'
foo, bar, baz
1, 2, 3
1,  , 3
 , 2,
1, 2, 3
'@ | ConvertFrom-Csv | Where-Object {
    -not [System.Linq.Enumerable]::Any(
        $_.PSObject.Properties.Value,
        [Func[object, bool]] { [string]::IsNullOrWhiteSpace($args[0]) })
}

相关问题