Subscribe via Email

Subscribe via RSS/JSON


Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan


Get a list of partitions and free space

The Win32_Volume class can be used to list partitions. The default output is very verbose but properties of interest to me are DriveLetter, Label, Capacity, and FreeSpace.

Ok, so let’s tidy this up a bit.

First, let’s get rid of any empty entries like the “System Reserved” partition.

Then let’s convert the capacity figure to GB and express free space as a percentage. This is easily done using Format-Table (I love playing with Format-Table to customize output! I find it tremendously exciting to be able to just format the output using an Expression script block).

Next let’s convert the capacity and free space figures to [uint32] so they get rounded as integers.

And lastly let’s include the label along with the drive letter.

Another useful property from Win32_Volume is DriveType.

This can be used to limit the output to only fixed disks, for instance. The numbers are constants that define the various types of drives (starting from the number 0) so it’s possible to filter by DriveType to limit to fixed disks only.

Just for kicks I’d like to put a % sign after each of the free space figures.

This one’s worth explaining a bit. The change that I made is in the Expression block for free space.

What I did is that I put [uint32]($_.FreeSpace/$_.Capacity*100) – the previous Expression block – within the $() operator so it is evaluated as a sub-expression. In turn I put the $() block within double quotes to type cast the number into a string. And finally I suffix the $() within double quotes with the “%” character so it’s appended to the string.

It’s important to use the $() operator here. Instead, if I had only grouped the code within brackets () what happens is that the expression $_.FreeSpace/$_.Capacity*100 gets evaluated as expected, but the result is not type cast to an integer as [uint32] is treated like a string rather than an operator due to the double quotes casting it that way. So the $() operator is required.

Since the number is a string it gets left-aligned. But that can easily be aligned to the right with the Align key:

See the next post for a different way of doing this.

Get a list of partitions and free space by rakhesh is licensed under a Creative Commons Attribution 4.0 International License.