Having used Get-Volume to find the free space on my PC’s C drive, I’d rather like to find out how much free space I have, as a percentage. You’d think we could just do the maths:
But as the error shows, $_.Size has evaluated to zero (hasn’t been found). Using the terms without the $_ gives a similar, if more verbose, result:
This is where Hash Tables come to the rescue. This simple syntax allows you to create expressions on the fly. I came across them a while back in this great resource: https://goo.gl/WLqAZx and once you’ve used them you’ll wonder how you ever did without them.
So, in our case we can now write a more useful query to determine the amount of space available on our C drive:
Get-Volume -DriveLetter C | Select Size, SizeRemaining, @{ Label=”PercentFree”; Expression={ 100 * ($_.SizeRemaining / $_.Size) } }
The @{ … } syntax has two main parts. The first is the label to be displayed for this new value. This is separated from the second part by a semi-colon. That second part is the expression to be evaluated, which itself is surrounded by braces.
You can use Get-Member to see how the new column of data has been added to the pipeline as part of the object selected:
As we can see, the result of the calculation is a Double and a NoteProperty. This makes it like any other field in the object and can be operated on further down the pipeline just like any other field.
Obviously this is not limited to Get-Volume but can be used anywhere a calculation needs to create a new data value in the pipeline.