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