File Length Needing to be displayed as either MB or GB in code

probably a real easy one here to answer:.

 

I am displaying a file size in a table that is very large.

 

I need the code for how to display that same number in the Length column in either MB or GB.

 

Please advise.

 

Thank you

Typically we help you with code that you’ve written that you’re having issues with. However you are in luck as I recently answered a question on Stackoverflow where the user needed to do the same thing with very large numbers.

Function Get-FriendlySize {
    Param([bigint]$bytes)
    switch($bytes){
        {$_ -gt 1PB}{"{0:N2} PB" -f ($_ / 1PB);break}
        {$_ -gt 1TB}{"{0:N2} TB" -f ($_ / 1TB);break}
        {$_ -gt 1GB}{"{0:N2} GB" -f ($_ / 1GB);break}
        {$_ -gt 1MB}{"{0:N2} MB" -f ($_ / 1MB);break}
        {$_ -gt 1KB}{"{0:N2} KB" -f ($_ / 1KB);break}
        default {"{0:N2} Bytes" -f $_}
    }
}

Call the function and pass in your number and it will return the formatted size. You may need to adjust this if you really only want MB or GB.

Get-FriendlySize 73068233
69.00 MB

Get-FriendlySize 5643986866
5.00 GB

Get-FriendlySize 91296907994238
83.00 TB