PowerShell display files size as KB, MB, or GB

I have a section of a PowerShell script that gets the file size of a specified directory.

I am able to get the values for different units of measurement into variables, but I don't know a good way to display the appropriate one.

$DirSize = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum)
$DirSizeKB = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum / 1KB)
$DirSizeMB = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum / 1MB)
$DirSizeGB = "{0:N2}" -f (($DirArray | Measure-Object -property length -sum).sum / 1GB)

If the number of bytes is at least 1 KB I want the KB value displayed. If the number of KBs is at least 1 MB I want MBs displayed and so on.

Is there a good way to accomplish this?


Use a switch or a set of "if" statements. Your logic (pseudocode) should look like this:

  1. Is the size at least 1 GB? Yes, display in GB (else...)
  2. Is the size at least 1 MB? Yes, display in MB (else...)
  3. Display in KB.

Note that you should be testing in reverse order from the largest size to the smallest. Yes, I could have written the code for you, but I suspect you know enough to turn the above into a working script. It's just the approach that had you stumped.