PSObject排序

时间:2013-09-16 10:09:46

标签: sorting powershell

我正在尝试格式化几天前与问题相关的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)对对象进行排序,但无济于事。它与字符串有关吗?

2 个答案:

答案 0 :(得分:3)

无法预测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

答案 1 :(得分:1)

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

$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()