更改对象中列的顺序 [英] Change order of columns in the object
问题描述
如何更改代码生成的输出的列顺序:
How can I change the column ordering of the output my code produces:
$apps = Import-CSV apps.csv
$computers = Import-CSV compobj.csv
foreach ($computer in $computers) {
$computerLob = $computer.lob
$lobApps = $apps | ? {$_.lob -eq $computerLob }
foreach ($app in $lobApps) {
$computerHostname = $computer.hostname
$appLocation = $app.location
$installed=Test-Path "\\$computerHostname\$appLocation"
New-Object PSObject -Property @{
Computer=$computer.hostname
App=$app.appname
Installed=$installed
}
}
目前它按以下顺序生成列:Installed,App,Computer
.
Currently it's producing the columns in the following order: Installed,App,Computer
.
我想按以下顺序安装它:Computer,App,Installed
.
I'd like to have it in the following order: Computer,App,Installed
.
推荐答案
如果您想确保对象的输出以特定顺序出现,即以特定方式格式化,请使用 PowerShell 的格式化命令.
If you want to ensure the output of an object occurs in a certain order i.e. formatted a certain way then use PowerShell's formatting commands.
$obj = [pscustomobject]@{Computer=$computer.hostname;App=$app.appname;Installed=$installed}
$obj | Format-Table Computer,App,Installed
更重要的是,您可以更好地控制输出,例如:
What's more you can better control the output e.g.:
$obj | Format-Table Computer,App,Installed -AutoSize
或者控制字段宽度&对齐:
Or control field width & alignment:
$obj | Format-Table @{label='Computer';expression={$_.Computer};width=20;alignment='right'},App,Installed
坦率地说,我认为使用格式化命令来获得您想要的输出顺序是更好的做法,而不是依赖于创建属性的顺序.
Frankly I think it is a better practice to use the formatting commands to get the output order you want rather than to rely upon the order in which the properties are created.
这篇关于更改对象中列的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!