我曾经有过同样的经历并创建了以下可重复使用的'Union
' 功能:
# 2021-08-25 Removed Union function
Usage:
$Obj1, $Obj2 | Union | Out-GridView -Title 'Showing all members'
它还应该适用于复杂的对象。一些标准 cmdlet 会一次输出多个对象类型,如果您查看它们(例如Out-GridView
)或将它们转储到文件中(例如Export-Csv
)你可能会错过很多属性。再举个例子:
Get-WmiObject -Namespace root/hp/instrumentedBIOS -Class hp_biosSetting | Union | Export-Csv ".\HPBIOS.csv"
2014年9月19日添加:
也许这已经是评论的字里行间了$Array | Select * | …
不会解决问题,但会专门选择属性$Array | Select Member1, Member2, Member3 | …
does.
此外,虽然在大多数情况下Union
函数将起作用,但有一些例外,因为它只会对齐first与其余的对象。
考虑以下对象:
$List = @(
New-Object PSObject -Property @{Id = 2}
New-Object PSObject -Property @{Id = 1}
New-Object PSObject -Property @{Id = 3; Name = "Test"}
)
If you Union
这个对象一切似乎都很好,如果你例如ExportTo-CSV
并与export .csv
从那时起你的文件将永远不会有任何问题。
$List | Union
Id Name
-- ----
2
1
3 Test
但仍然存在一个问题,因为只有第一个对象被对齐。如果你例如对结果进行排序Id
(Sort Id
) 或仅取最后 2 个 (Select -Last 2
)条目,Name
未列出,因为第二个对象不包含Name
财产:
$List | Union | Sort Id
Id
--
1
2
3
因此我重写了Union-Object
(Alias Union
) 函数`):
联合对象
# 2021-08-25 Removed Union-Object function
Syntax:
$Array | Union | Out-GridView -Title 'All members correctly displayed'
更新2021-08-25
Based on az1d https://stackoverflow.com/users/827369/az1d helpful feedback on an error caused by equal property names with different casing, I have created a new UnifyProperties
function.
(I will no longer use the name UnionObject
for his)
function UnifyProperties {
$Names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
$InputCollected = @($Input)
$InputCollected.ForEach({
foreach ($Name in $_.psobject.Properties.Name) { $Null = $Names.Add($Name) }
})
$inputCollected | Select-Object @($Names)
}
Usage:
[pscustomobject] @{ one = 1; two = 2; three = 3 },
[pscustomobject] @{ ONE = 10; THREE = 30; FOUR = 4 } |
UnifyProperties
one two three FOUR
--- --- ----- ----
1 2 3
10 30 4
也可以看看:#13906将 -UnifyProperties 参数添加到 Select-Object https://github.com/PowerShell/PowerShell/issues/13906