PowerShell for Windows Admins

Jun 13 2011   3:06PM GMT

Calculated Fields

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: