PowerShell 将文件大小显示为 KB、MB 或 GB [英] PowerShell display files size as KB, MB, or 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 的数量至少为 1MB,我希望显示 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:
- 大小是否至少为 1GB?是的,以 GB 显示(否则...)
- 大小是否至少为 1MB?是的,以 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.
这篇关于PowerShell 将文件大小显示为 KB、MB 或 GB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!