我在我的函数中构建了以下CustomObject
New-Object -Type PSCustomObject -Property @{
Computername = $_
PowerShellVersion = $result[0]
dotNetVersion = $result[1]
sqlnacli = $result[2]
redistributable = $result[3]
}
但输出是这样的:
PowerShellVersion Computername redistributable sqlnacli dotNetVersion
----------------- ------------ --------------- -------- -------------
3+ OK SERVERNAME NOT OK NOT OK NOT OK
为什么PowerShell会重新排列我的对象的顺序,如何强制它接受我想要的顺序?
答案 0 :(得分:7)
根据定义,不按顺序排列哈希表。如果您有PowerShell v3.0或更高版本,则可以使用哈希表的[Ordered]
属性:
New-Object PSCustomObject -Property ([Ordered] @{
Computername = $_
PowerShellVersion = $result[0]
dotNetVersion = $result[1]
sqlnacli = $result[2]
redistributable = $result[3]
})
在PowerShell v3 +中,您也可以使用[PSCustomObject]
类型加速器:
[PSCustomObject] @{
Computername = $_
PowerShellVersion = $result[0]
dotNetVersion = $result[1]
sqlnacli = $result[2]
redistributable = $result[3]
}
如果您需要PowerShell版本2兼容性,则可以使用
New-Object PSObject -Property @{
Computername = $_
PowerShellVersion = $result[0]
dotNetVersion = $result[1]
sqlnacli = $result[2]
redistributable = $result[3]
} | Select-Object Computername,PowerShellVersion,dotNetVersion,sqlnacli,redistributable
此方法的缺点是,如果添加属性,则必须记住将它们添加到Select-Object
。
替代PowerShell v2或更早版本是输出内容(例如,空字符串),然后使用Select-Object
创建所需的自定义属性:
$obj = $_
"" | Select-Object `
@{Name = "Computername"; Expression = {$obj}},
@{Name = "PowerShellVersion"; Expression = {$result[0]}
@{Name = "dotNetVersion"; Expression = {$result[1]}
@{Name = "sqlnacli"; Expression = {$result[2]}
@{Name = "redistributable"; Expression = {$result[3]}
这里唯一(次要)的缺点是$_
中的Select-Object
指的是从中选择属性的前一个对象(因此$obj = $_
作为第一行,保留价值。)
答案 1 :(得分:3)
正如@wOxxOm和@Bill_Stewart所提到的,你需要一个有序的哈希表来指示顺序,默认情况下,标准哈希表不是。您可以使用select语句影响普通哈希表的顺序,如下所示。
New-Object -Type PSCustomObject -Property @{
Computername = $_
PowerShellVersion = $result[0]
dotNetVersion = $result[1]
sqlnacli = $result[2]
redistributable = $result[3]
} | Select-Object Computername,PowerShellVersion,dotNetVersion,sqlnacli,redistributable