我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重新排列我的对象的顺序,我怎么能强迫它采取我想要的顺序?
根据定义,不按顺序排列哈希表.如果您有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]}}
这里唯一(次要)的缺点是$_
in Select-Object
指的是从中选择属性的前一个对象(因此$obj = $_
作为第一行,保留值).