powershell PSObject排序

368yc8dk  于 2023-05-22  发布在  Shell
关注(0)|答案(3)|浏览(169)

我正在尝试格式化一个与几天前的一个问题相关的PSObject。我的对象看起来像这样:

New-Object PSObject -Property @{
    "Version"= $winVersion.Caption
    "Processor Name" = $processorInfo.Name
    "Processor Manufacturer" = $processorInfo.Manufacturer
    "Processor Max Clock Speed" = $processorInfo.MaxClockSpeed     
} |format-list

上面给出了以下输出:

Processor Manufacturer    : GenuineIntel
Processor Max Clock Speed : 2201
Version                   : Microsoft Windows 8 Pro
Processor Name            : Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz

然而,这:

New-Object PSObject -Property @{
    "Windows Version"= $winVersion.Caption
    "Processor Name" = $processorInfo.Name
    "Processor Manufacturer" = $processorInfo.Manufacturer
    "Processor Max Clock Speed" = $processorInfo.MaxClockSpeed     
} |format-list

给出以下输出:

Processor Manufacturer    : GenuineIntel
Processor Max Clock Speed : 2201
Processor Name            : Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz
Windows Version           : Microsoft Windows 8 Pro

这不是什么大问题,但我想知道为什么格式会改变?它似乎不是按字母顺序排列的。此外,我尝试使用Sort-Object(从A-Z)对对象进行排序,但没有效果。是否与String有关?

bxjv4tth

bxjv4tth1#

hashtable的顺序无法预测(in PowerShell V3.0 you can user the [ordered] accelerator to make an hashtable ordered),但在V2.0中,您需要像这样构建自定义对象以保留属性顺序:

$o = New-Object PSObject
 $o | add-member Noteproperty  "Version"  $winVersion.Caption
 $o | add-member Noteproperty  "Processor Name" $processorInfo.Name
 $o | add-member Noteproperty  "Processor Manufacturer" $processorInfo.Manufacturer
 $o | add-member Noteproperty  "Processor Max Clock Speed" $processorInfo.MaxClockSpeed

$o | format-list
fcy6dtqo

fcy6dtqo2#

您仍然可以向对象添加自定义方法以提供所需的格式,例如:

$test = New-Object PSObject -Property @{
    "Processor Manufacturer"="GenuineIntel"
    "Processor Max Clock Speed" = "2201"
    "Version"="Microsoft Windows 8 Pro"
}
Add-Member -MemberType ScriptMethod -Name "show" -Value {echo $this.version;echo $this."processor manufacturer";echo $this."Processor Max Clock Speed"} -inputObject $test

$test.show()
lnvxswe2

lnvxswe23#

这一点:

new-object psobject -property ([ordered]@{key1=$value1; key2=$value2})

相关问题