如何保持 psobject 有序?

2023-12-23

我有以下脚本,它从另一个脚本获取对象并将其转换为 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 https://stackoverflow.com/a/42300930/8397835

$Arr += [pscustomobject]$customObj

但这不起作用。我尝试将转换放在函数的其他位置并给出了错误。

只能在散列文字节点上指定有序属性。

我想我不确定我应该把它放在哪里[ordered] or [pscutomobject]在函数中,因为就我而言,我没有@ symbol


这个问题(据我所知)都是关于复制对象属性,同时保持属性顺序不变。
The Get-Member(gm) cmdlet 不保留输入对象中设置属性的顺序,而是迭代PSObject.属性 https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.psobject.properties?view=powershellsdk-1.1.0 does.

对于 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

$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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何保持 psobject 有序? 的相关文章

随机推荐