开发者

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

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 a开发者_开发问答lign the value to right?


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


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.


here is an ugly looking one liner that builds from several other threads:

Get-WmiObject win32_LogicalDisk | where { $_.DriveType -eq 3 } | Format-Table DeviceID,VolumeName,@{N="Size";E={'{0:N0}' -f $_.Size};a="right"},@{N="FreeSpace";E={'{0:N0}' -f $_.FreeSpace};a="right"},@{N="Used";E={'{0:N0}' -f ($_.Size - $_.FreeSpace)};a="right"}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜