并非显示所有属性

Dar*_*te1 6 arrays powershell properties

当我们尝试通过管道将数据导出到其他函数时,我们在PowerShell中观察到一些奇怪的行为.

示例代码:

$Array = @()

$Obj1 = [PSCustomObject]@{
    Member1   = 'First'
    Member2   = 'Second'
}

$Obj2 = [PSCustomObject]@{
    Member1   = 'First'
    Member2   = 'Second'
    Member3   = 'Third'
}

$Array = $Obj1, $Obj2
$Array | Out-GridView -Title 'Not showing Member3'

$Array = $Obj2, $Obj1
$Array | Out-GridView -Title 'All members correctly displayed'
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,您可以看到当第一个对象仅包含2时properties,Out-GridViewCmdLet(和其他)仅显示2 properties,即使第二个对象具有3 properties.但是,当数组中的第一个对象有3时,properties它会正确地显示它们.

有没有解决的办法?因为不可能预先properties确定一个物体上有多少物体,并且物体中最多的物体properties将是第一个物体array.

iRo*_*Ron 5

我曾经有过相同的经历并创建了以下可重复使用Union的功能:

Function Union {
    $Union = @()
    $Input | ForEach {
        If ($Union.Count) {$_ | Get-Member | Where {!($Union[0] | Get-Member $_.Name)} | ForEach {$Union[0] | Add-Member NoteProperty $_.Name $Null}}
        $Union += $_
    }
    $Union
}
Run Code Online (Sandbox Code Playgroud)

用法:

$Obj1, $Obj2 | Union | Out-GridView -Title 'Showing all members'
Run Code Online (Sandbox Code Playgroud)

它也应该用于复杂的对象.某些标准cmdlet一次输出多个对象类型,如果您查看它们(例如Out-GridView)或将它们转储到文件中(例如Export-Csv),您可能会错过很多属性.再举一个例子:

Get-WmiObject -Namespace root/hp/instrumentedBIOS -Class hp_biosSetting | Union | Export-Csv ".\HPBIOS.csv"
Run Code Online (Sandbox Code Playgroud)

新增2014-09-19:

也许这已经在评论中的行之间$Array | Select * | …不会解决问题,但具体选择属性呢$Array | Select Member1, Member2, Member3 | ….
此外,虽然在大多数情况下Union函数都可以工作,但是有一些例外,因为它只会将第一个对象与其余对象对齐.考虑以下对象:

$List = @(
    New-Object PSObject -Property @{Id = 2}
    New-Object PSObject -Property @{Id = 1}
    New-Object PSObject -Property @{Id = 3; Name = "Test"}
)
Run Code Online (Sandbox Code Playgroud)

如果你Union这个对象看起来很好,如果你从那时开始ExportTo-CSV使用该export .csv文件就不会有任何问题.

$List | Union
Id Name
-- ----
 2
 1
 3 Test
Run Code Online (Sandbox Code Playgroud)

仍有一个问题,因为只有第一个对象是对齐的.如果您例如对结果进行排序Id(Sort Id)或仅采用最后的2(Select -Last 2)条目,Name则不会列出,因为第二个对象不包含该Name属性:

$List | Union | Sort Id
Id
--
 1
 2
 3
Run Code Online (Sandbox Code Playgroud)

因此我重写了Union-Object(Alias Union)函数` ):

联盟对象

Function Union-Object ([String[]]$Property = @()) {         # Version 00.02.01, by iRon
    $Objects = $Input | ForEach {$_}
    If (!$Property) {ForEach ($Object in $Objects) {$Property += $Object.PSObject.Properties | Select -Expand Name}}
    $Objects | Select ([String[]]($Property | Select -Unique))
} Set-Alias Union Union-Object
Run Code Online (Sandbox Code Playgroud)

句法:

$Array | Union | Out-GridView -Title 'All members correctly displayed'
Run Code Online (Sandbox Code Playgroud)

有关最新Union-Object版本,请参阅:https://powersnippets.com/union-object/