The Usual Tech Ramblings

PowerShell; Calculated values in results

Whilst sitting here on a product release call, I was reading over my twitter feed, specifically looking at #powershell, and I saw a post by @tonjoh. Feeling I had a few minutes on my hands whilst QA bashed away at the servers, I decided to take a look…

I’m not sure what WMI counter is being used as I cannot find one called free-diskspace-query, but I do know there is a Win32_LogicalDisk, which has enough information in it to tell us free space. So here we go… Lets just get the information we want first, and build up from there…

Get-WmiObject Win32_LogicalDisk | Format-Table DeviceId, Size, FreeSpace

This is pretty simple, and can probably be found as an example all over the place. For the curious, the output looks like this:

DeviceId                   Size                     FreeSpace
--------                   ----                     ---------
C:                 119941029888                   48341823488

So we can see the size (~111GB), and the amount of free space (~45GB). Now onto the fun stuff, using expressions.

Expressions allow us to do calculations on the resultset that came back from the pre-piped data. This can be something like calculating a percentage, or throwing in miscellaneous data (like requested, a timestamp).

Get-WmiObject Win32_LogicalDisk | `
    Format-Table DeviceId, Size, FreeSpace, `
    @{Name="PercFree";Expression={[int]($_.FreeSpace/$_.Size * 100)}}, `
    @{Name="ReportDate";Expression={(Get-Date -Format "yyyyMMdd-HHMMss")}}

In the above code, I’ve used the back-tick (`) to wrap the lines, and make it easier to read. PowerShell understands this, and will treat the 4 lines as one. I’ve created 2 extra, named, columns, one PercFree, and the other ReportDate. The expression in the first is a calculation based on the values from the Win32_LogicalDisk output, whilst the expression for the second is just extra data in the form of a formatted date. With the above code, you get the following…

DeviceId           Size    FreeSpace   PercFree ReportDate                   
--------           ----    ---------   -------- ----------                   
C:         119941029888  48297115648         40 20100611-040646

And there we have it, two extra columns, which were calculated on the fly.