Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: align right for a column value from Select-Object in Format-Table format

Tags:

powershell

I have the following array value $outData with several columns. I am not sure how I align some columns right?

$outData | Select-Object `
      Name `
      @{Name="Freespace(byte)"; Expression={"{0:N0}" -f $_.FreeSpace}}, '
      .... # other colums `
 | Format-Table -AutoSize

It works fine. However, when I tried to use align for the freespace column to right:

      @{Name="Freespace(byte)"; Expression={"{0:N0}" -f $_.FreeSpace}; align="right"}, '

I got error message "Specified method is not supported". Not sure if there is any way to align the value to right?

like image 431
David.Chu.ca Avatar asked Apr 28 '10 17:04

David.Chu.ca


2 Answers

The align directive goes in a hashtable that is specified to the Format-Table cmdlet. IOW, align is not a supported hashtable entry for Select-Object. So make sure to do your formatting via hashtables in the hashtable passed to Format-Table e.g.:

gps | select name,pm | format-table @{n='Name';e={$_.Name};align='right'},PM

or in your case:

$outData | Format-Table Name,
                  @{n="Freespace(byte)";e={"{0:N0}" -f $_.FreeSpace};a="right"}
like image 64
Keith Hill Avatar answered Nov 14 '22 23:11

Keith Hill


Given the updates to Powershell in the last 8 years, this answer may not have existed in '10.

The trick is to assign a number of columns within the calculated expression's format block {0:N0}, once assigned, it will align the column to the right.

In the original example, include ,15 as part of the number formatting:

@{Name="Freespace(byte)"; Expression={"{0,15:N0}" -f $_.FreeSpace}}

I generally use the character count of the Name= value to ensure the entire name is visible.

like image 33
treacle Avatar answered Nov 14 '22 23:11

treacle