PowerShell将文件大小显示为KB,MB或GB [英] PowerShell display files size as KB, MB, or GB

查看:501
本文介绍了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. 大小至少为1 GB吗?是的,以GB显示(其他...)
  2. 大小至少为1 MB吗?是的,以MB显示(其他...)
  3. 以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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆