Outputting File Sizes in Different Formats

by Nov 18, 2015

When you store a number in a variable, you may want to display the number in different units. Bytes are very precise, but sometimes displaying the bytes as kilobytes or megabytes would be more appropriate.

Here is a clever trick that overwrites the internal ToString() method with a more versatile one: it takes a unit, the number of digits you want, and the text of a suffix. This way, you can display the number in various formats, just as needed.

The content stays untouched, so the variable still holds an integer value that you can safely sort or compare to other values:

#requires -Version 1

$a = 1257657656
$a = $a | Add-Member -MemberType ScriptMethod -Name tostring -Force -Value { param($Unit = 1MB, $Digits=1, $Suffix=' MB') "{0:n$Digits}$Suffix" -f ($this/($Unit)) } -PassThru

And here are some examples on how you can use $a now:

PS> $a
1.199,4 MB

PS> $a.ToString(1GB, 0, ' GB')
1 GB

PS> $a.ToString(1KB, 2, ' KB')
1.228.181,30 KB

PS> $a -eq 1257657656

PS> $a -eq 1257657657

PS> $a.GetType().Name 

Twitter This Tip! ReTweet this Tip!