PowerShell helper function to return readable storage sizes

I came across this code whilst looking through the built-in cmdlets that come with Windows 8.x. The function was located in storage.format.ps1xml and is used to format disk capacities in list and table views, so all credit goes to Microsoft for this one.

I’ve since appropriated it as a helper function in another WMI/CIM-related script, as it’s quite handy for converting the raw byte values that Get-CimInstance returns.

function ReadableStorage ($size) {
    $postfixes = @( "B", "KB", "MB", "GB", "TB", "PB" )
    for ($i=0; $size -ge 1024 -and $i -lt $postfixes.Length - 1; $i++) { $size = $size / 1024; }
    return "" + [System.Math]::Round($size,2) + " " + $postfixes[$i];

Here are some examples of it in action:

PS C:> ReadableStorage(1024)
1 KB

PS C:> ReadableStorage(2147483648)
2 GB

PS C:> ReadableStorage(12384898975268864)
11 PB

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s