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

I have the following value of a $ outData array with multiple columns. I'm not sure how to align some columns correctly?

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

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

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

The error message "The specified method is not supported." Not sure if there is a way to align the value to the right?

+4
source share
2 answers

The align directive is in the hash table that is specified on the Format-Table cmdlet. IOW, align is not supported by the hash table for Select-Object. Therefore, be sure to do your formatting using hash tables in the hash table passed to the format table, for example:

 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"} 
+5
source

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

The trick is to assign the number of columns in the format block of the calculated expression {0:N0} , after it is 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 usually use the number of characters of the Name = value to make sure the entire name is visible.

+1
source

Source: https://habr.com/ru/post/1308270/


All Articles