Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change order of columns in the object

Tags:

powershell

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
        }
    }

Currently it's producing the columns in the following order: Installed,App,Computer.

I'd like to have it in the following order: Computer,App,Installed.

like image 772
theshizy Avatar asked Oct 27 '13 22:10

theshizy


2 Answers

Powershell V3 added a type accelerator for [PSCustomObject] that creates objects using an ordered hash table, so the properties stay in the order they're declared:

[PSCustomObject] @{
  Computer=$computer.hostname
  App=$app.appname
  Installed=$installed
}
like image 191
mjolinor Avatar answered Sep 24 '22 06:09

mjolinor


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.

like image 23
Keith Hill Avatar answered Sep 25 '22 06:09

Keith Hill