PowerShell display files size as KB, MB, or GB

batch-file, powershell, scripting

Solution

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

- Is the size at least 1 GB? Yes, display in GB (else...)

- Is the size at least 1 MB? Yes, display in MB (else...)

- 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.

Problem

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?

Original source

Related problems