In the previous post I wanted to convert some output to percentage figures and resorted to type casting to get it done. Turns out I don’t need to do that. Was reading more about the Format-Table
cmdlet and saw that the hash table that supplies calculated properties also supports a key called FormatString
which let’s one specify the format of the output.
For a quick overview of FormatString
read this MSDN page. You can see various format specifier strings mentioned there. These let you define the format of the output.
Say I want to see the current time and output the remaining minutes to the hour as a percentage.
I can get the current minute thus:
1 |
get-date | ft Minute -AutoSize |
I can use an Expression
block to show the balance minutes:
1 |
get-date | ft @{Name="Bal Min"; Expression={(60-$_.Minute)/60}} -AutoSize |
And if I want to format the output such that it’s shown as a percentage (the value multiplied by 100 with a % sign suffixed) I can use FormatString
with the “P” format specifier:
1 |
get-date | ft @{Name="Bal Min"; Expression={(60-$_.Minute)/60}; FormatString="P"} -AutoSize |
This gives the output as a percentage figure with two decimal places (the default). I can modify that by suffixing a number to the “P” specifying the desired number of decimal places. Like for instance:
1 |
get-date | ft @{Name="Bal Min"; Expression={(60-$_.Minute)/60}; FormatString="P1"} -AutoSize |
If I want to round, I can use the “r” specifier. I can do decimal, scientific, fixed point, and so on.
Returning to the code of the previous post, here’s a revised version:
1 2 |
gwmi Win32_volume | ` ?{ ($_.DriveLetter -notmatch "^$") -and ($_.DriveType -eq 3) } | ft DriveLetter,Label,@{Name="Capacity"; Expression={$_.Capacity/1024/1024/1024}; FormatString="F0"},@{Name="FreeSpace"; Expression={ $_.FreeSpace/$_.Capacity }; FormatString = "P1"} |
There’s two changes: (1) I don’t type cast the Capacity to [uint32]
any more to round it, rather I use the “F0” format specifier which stands for a fixed-point number with 0 decimal digits (i.e. a number like 42.9517669677734 gets converted to 43); (2) I don’t type cast for the free space to percentage either, I just use the “P1” format specifier which stands for a percentage figure with 1 decimal digit (i.e. a number like 48.6%).
Neat!