我正在导入一个csv文件,如下所示:
id,value1.1,value1.2,value1.3,Value2.1,Value2.2,Value3.1,Value3.2
row1,v1.1,,v1.3
row2,,,,v2.1,v2.2
row3,,,,,,,v3.2
现在我想检查一个组中是否设置了任何值属性。
我能做到
Import-Csv .\test.csv | where {$_.Value1.1 -or $_.Value1.2 -or $_.Value1.3}
或
Import-Csv .\test.csv | foreach {
if ($_.Value1 -or $_.Value2 -or $_.Value3) {
Write-Output $_
}
}
但我的“真正的”csv文件包含大约200列,我必须检查31个属性x 5个在此csv中混合的不同对象类型。所以我的代码真的很难看。
是否有类似
的内容where {$_.Value1.*}
或
where {$ArrayWithPropertyNames}
答案 0 :(得分:0)
您可以轻松使用Get-Member cmdlet获取具有正确前缀的属性(仅使用*
作为前缀后面的通配符)。
因此,要实现您想要的功能,您可以根据具有正确前缀的任何属性是否包含数据来过滤数据。
下面的脚本使用您添加了row4
的示例数据,并对列表进行过滤,以查找在以value1
开头的任何属性中具有值的所有项目。
$csv = @"
id,value1.1,value1.2,value1.3,Value2.1,Value2.2,Value3.1,Value3.2
row1,v1.1,,v1.3
row2,,,,v2.1,v2.2
row3,,,,,,,v3.2
row4,v1.1,,v1.3
"@
$data = ConvertFrom-csv $csv
$data | Where {
$currentDataItem = $_
$propertyValues = $currentDataItem |
# Get's all the properties with the correct prefix
Get-Member 'value1*' -MemberType NoteProperty |
# Gets the values for each of those properties
Foreach { $currentDataItem.($_.Name) } |
# Only keep the property value if it has a value
Where { $_ }
# Could just return $propertyValues, but this makes the intention clearer
$hasValueOnPrefixedProperty = $propertyValues.Length -gt 0
Write-Output $hasValueOnPrefixedProperty
}
答案 1 :(得分:0)
替代解决方案:
$PropsToCheck = 'Value1*'
Import-csv .\test.csv |
Where {
(($_ | Select $PropsToCheck).psobject.properties.value) -contains ''
}