我有一个对象数组,我从一个带有Invoke-SqlCmd的SQL表中读取了这些对象,如下所示:
ARTIKEL_NR : 74.10095.00
ArtBeschrieb1_3 : Onyx RGB-Strip 14W/m 24V DC Samsung
KLASSE : LuXLED
SMB1 :
SMW1 :
SMN1 :
SMB2 : Leistung
SMW2 : 14 W/m
SMN2 :
SMB3 : Lichtfarbe
SMW3 : RGB;但是有了更多的财产,大约80。
现在,我想过滤掉所有的空属性,而不是显式地声明它们。所以上面的例子最终应该是这样的:
ARTIKEL_NR : 74.10095.00
ArtBeschrieb1_3 : Onyx RGB-Strip 14W/m 24V DC Samsung
KLASSE : LuXLED
SMB2 : Leistung
SMW2 : 14 W/m
SMB3 : Lichtfarbe
SMW3 : RGB;我怎么能这么做?
我知道我可以使用[string]::IsNullOrEmpty()或[string]::IsNullOrWhiteSpace(),但是我不知道如何在不显式列出属性的情况下检查它们--我的意思是:
Where-Object { ![string]::IsNullOrEmpty($_.SMB1) -and ![string]::IsNullOrEmpty($_.SMW1) -and ... }..。因为如果我要打字的话,我的手指就会断裂
发布于 2021-01-06 14:46:39
对象有一个名为MemberSet的psobject,它包含对象的属性。您可以运行$object.psobject.Properties来查看属性对象。对于您提供的对象,可以执行如下操作:
$object | Select ($object.psobject.Properties | Where Value).Name如果有一个包含每个对象可能具有不同的空属性的对象的数组,则可以在数组中的每个对象执行上述筛选:
$array | Foreach-Object {
$_ | Select ($_.psobject.Properties | Where Value).Name
}如果数组中的第一个对象具有4个或更少的属性,则该选项有一个警告,则默认显示将是表视图。表视图将只显示与第一个对象对应的属性。因此,如果$array[0]只包含没有空值的SMB3,那么$array[1]将只显示SMB3等等。--这只是一个显示问题,因为实际数据是准确的。要解决这个问题,需要强制列表视图:
$array | Foreach-Object {
$_ | Select ($_.psobject.Properties | Where Value).Name
} | Format-List发布于 2021-01-06 14:59:42
试试看以下几点。使用摘要哈希集之后,您可以重新创建一个统一的数组,否则当使用我的脚本中提到的cmdlet时,会丢失一些属性。
$inputData = <your-sql-result>
<#
summary of all properties required for properly output the data afterwards,
when used with cmdlets like Out-GridView, Export-Csv, ConvertTo-Csv, etc
otherwise some properties are missing, because such cmdlets gets the properties only from first index
#>
$propertySummary = [System.Collections.Generic.HashSet[string]]::new()
$output = foreach ($item in $inputData) {
$newProperties = [ordered]@{}
foreach ($property in $item.psobject.properties) {
if (![string]::IsNullOrEmpty($property.Value)) {
$newProperties.Add($property.Name, $property.Value)
# add to summary
[void]$propertySummary.Add($property.Name)
}
}
[pscustomobject]$newProperties
}
# output with missing properties
$output | Out-GridView -Title 'Missing properties'
# correct output with all properties
$output | Select-Object -Property ([string[]]$propertySummary) | Out-GridView -Title 'Correct'https://stackoverflow.com/questions/65597475
复制相似问题