PowerShell将文件大小显示为KB,MB或GB
我有一个PowerShell脚本的一部分,可以获取指定目录的文件大小.
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)
如果字节数至少为1 KB,我希望显示KB值.如果KB的数量至少为1 MB,我希望显示MB,依此类推.
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?
使用开关或一组"if"语句.您的逻辑(伪代码)应如下所示:
Use a switch or a set of "if" statements. Your logic (pseudocode) should look like this:
- 大小至少为1 GB吗?是的,以GB显示(其他...)
- 大小至少为1 MB吗?是的,以MB显示(其他...)
- 以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.