如何保持psobject的顺序?

时间:2019-07-13 20:16:51

标签: powershell

我有以下脚本,该脚本从另一个脚本获取对象并将其转换为pscustomobject

& ".\script1.ps1" -ViewConnection "$cinput" -OutVariable xprtOut | Format-Table -Wrap

#converting xprtOut from Arraylist to pscustomobject to be used with ConvertTo-HTMLTable
$Arr = @()
foreach ($Object in $xprtOut) {
    $i = -1
    $arrayListCount = -($Object | gm | Where-Object {$_.MemberType -like "noteproperty"}).Count

    $customObj = New-Object PSCustomObject
    do {
        $customObj | Add-Member -MemberType NoteProperty -Name (($Object | gm)[$($i)].Name) -Value ($Object."$(($Object | gm)[$($i)].Name)")
        $i--
    } while ($i -ge $arrayListCount)

    $Arr += $customObj
}

它很好用,但我注意到所有对象的顺序都在变化。 如何保留函数中的顺序?

我在这里尝试答案:https://stackoverflow.com/a/42300930/8397835

$Arr += [pscustomobject]$customObj

但这不起作用。我试图将演员表放置在函数中的其他地方,并给出了错误。

  

只能在哈希文字节点上指定有序属性。

我想我不确定应该将[ordered][pscutomobject]放在函数中的哪个位置,因为在我的情况下,我没有@符号

1 个答案:

答案 0 :(得分:1)

(如我所见),这个问题是所有关于复制对象属性同时保持属性顺序正确的问题。
Get-Member(gm)cmdlet不会保持在输入对象中设置属性的顺序,但是会迭代PSObject.Properties

对于PowerShell 3.0及更高版本:

$Arr = foreach ($Object in $xprtOut) {
    # create an empty PSCustomObject
    $copy = [PSCustomObject]::new()
    # loop through the properties in order and add them to $copy object
    $Object.PSObject.Properties | ForEach-Object { 
        $copy | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Value
    }
    # emit the copied object so it adds to the $Arr array
    $copy
}

如果您使用的是PowerShell <3.0,请使用以下代码:

$Arr = foreach ($Object in $xprtOut) {
    # create an ordered dictionary object
    $copy = New-Object System.Collections.Specialized.OrderedDictionary
    # loop through the properties in order and add them to the ordered hash
    $Object.PSObject.Properties | ForEach-Object { 
        $copy.Add($_.Name, $_.Value)   # or use: $copy[$($_.Name)] = $_.Value
    }
    # emit a PSObject with the properties ordered, so it adds to the $Arr array
    New-Object PSObject -Property $copy
}