header image

Calculated Fields

Posted by: | June 13, 2011 | No Comment |

You have probably seen something like this many times

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
select @{Name="FreeSpace";Expression={$_.Freespace / 1GB}}

We take an object and perform a calculation to in effect make a new property – a calculated field. Label can be used instead of Name if desired in PowerShell 2

This can also be done in Format-Table

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}}

There some other parameters we can use

We can control the alignment in the field

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Alignment="Left"}

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Alignment="Center"}

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Alignment="Right"}

We can format the string

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Format="F2"; Alignment="Left"}

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Format="F2"; Alignment="Center"}

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Format="F2"; Alignment="Right"}

And we can control the width of the string

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Width=11; Format="F2"; Alignment="Left"}

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Width=11; Format="F2"; Alignment="Center"}

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" |
Format-Table @{Name="FreeSpace";Expression={$_.Freespace / 1GB}; Width=11; Format="F2"; Alignment="Right"}

 

Width, format and alignment don’t work with select-object

under: PowerShellV2