Recently I’ve been asked several times to write a script to create a report about storage usage… going from simple file sizes and directory sizes to storage utilization within virtual machines. Every single time I got to the point where I needed to decide on the output… in MB? GB? Or just plain bytes?
This is not a proper way to do this… to do it right, the script would need to look at the size of the object and decide per object what size format it should use
Now, here’s a handy reusable function that takes the size (or ‘length’ as the size property is named) of a file as a mandatory input, calculates which size format is most appropriate and provides this as an output…
function Select-SizeFormatType
{
# Define the mandatory input parameter
param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)][System.int64]$sizeInBytes)
switch ($SizeInBytes)
{
# Determine the correct size format and use ‘break’ to exit the switch
{$SizeInBytes -ge 1TB} {“{0:n$sigDigits}” -f ($SizeInBytes/1TB) + ” TB” ; break}
{$SizeInBytes -ge 1GB} {“{0:n$sigDigits}” -f ($SizeInBytes/1GB) + ” GB” ; break}
{$SizeInBytes -ge 1MB} {“{0:n$sigDigits}” -f ($SizeInBytes/1MB) + ” MB” ; break}
{$SizeInBytes -ge 1KB} {“{0:n$sigDigits}” -f ($SizeInBytes/1KB) + ” KB” ; break}
Default { “{0:n$sigDigits}” -f $SizeInBytes + ” Bytes” }
}
}

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 