2017-08-30 269 views
0

我有一个表单,当单击按钮时显示配置文件夹的大小。这里有几个代码的变化我已经试过了图片文件夹...如何根据文件大小显示KB,MB或GB文件夹的大小?

$Pictures_Size = (Get-ChildItem $User\Pictures -recurse | Measure-Object -property length -sum) 
    $Pictures_Size_KB = "{0:N2}" -f ($Pictures_Size.sum/1KB) 
    $Pictures_Size_MB = "{0:N2}" -f ($Pictures_Size.sum/1MB) 
    $Pictures_Size_GB = "{0:N2}" -f ($Pictures_Size.sum/1GB) 
    If ($Pictures_Size_KB -gt 1024) { $Pictures_Box.Text = "Pictures - $($Pictures_Size_MB) MB" } 
    If ($Pictures_Size_MB -gt 1024) { $Pictures_Box.Text = "Pictures - $($Pictures_Size_GB) GB" } 
    Else { $Pictures_Box.Text = "Pictures - $($Pictures_Size_KB) KB" } 

$Pictures_Size = (Get-ChildItem $User\Pictures -recurse | Measure-Object -property length -sum) 
    $Pictures_Size_KB = "{0:N2}" -f ($Pictures_Size.sum/1KB) 
    $Pictures_Size_MB = "{0:N2}" -f ($Pictures_Size.sum/1MB) 
    $Pictures_Size_GB = "{0:N2}" -f ($Pictures_Size.sum/1GB) 
    If ($Pictures_Size_MB -ge 1024) { $Pictures_Box.Text = "Pictures - $($Pictures_Size_GB) GB" } 
    If ($Pictures_Size_MB -lt 1024) { $Pictures_Box.Text = "Pictures - $($Pictures_Size_MB) MB" } 
    If ($Pictures_Size_KB -lt 1024) { $Pictures_Box.Text = "Pictures - $($Pictures_Size_KB) KB" } 

图片文件夹,我的测试是5 MB,但它显示为0.00 GB ,我无法弄清楚为什么。在第一个代码示例中,如果我取出If ($Pictures_Size_MB -gt 1024)一行,它将在5.05 MB处正确显示大小。我不确定有什么问题,因为5小于1024,所以它不应该显示GB编号。

请注意,这也需要在Windows 7中工作!

谢谢!

+0

[Powershell显示文件大小为KB,MB或GB](https://stackoverflow.com/questions/24616806/powershell-display-file-size-as- kb-mb-or-gb) – BACON

回答

1

我用这个代码很多次:

# PowerShell Script to Display File Size 
Function Format-DiskSize() { 
[cmdletbinding()] 
Param ([long]$Type) 
If ($Type -ge 1TB) {[string]::Format("{0:0.00} TB", $Type/1TB)} 
ElseIf ($Type -ge 1GB) {[string]::Format("{0:0.00} GB", $Type/1GB)} 
ElseIf ($Type -ge 1MB) {[string]::Format("{0:0.00} MB", $Type/1MB)} 
ElseIf ($Type -ge 1KB) {[string]::Format("{0:0.00} KB", $Type/1KB)} 
ElseIf ($Type -gt 0) {[string]::Format("{0:0.00} Bytes", $Type)} 
Else {""} 
} # End of function 
$BigNumber = "230993200055" 
Format-DiskSize $BigNumber 

来源:http://www.computerperformance.co.uk/powershell/powershell_function_format_disksize.htm

+0

这工作完美,谢谢! – sloppyfrenzy

0

$Pictures_Size_MB包含字符串"5.05",它大于整数1024,这就是满足条件的原因。

+0

它如何确定5.05大于1024? – sloppyfrenzy

+0

我不是PowerShell的专家,但它似乎是将字符串与数字进行比较,因此它将数字转换为字符串,然后将“5.05”与“1024”“进行比较。如果按字符比较它,则5大于1,因此5.05字符串比1024字符串“大”。 –

+0

我想,但它适用于KB> MB。 – sloppyfrenzy

1

当你使用的-f运营商,你的输出(这里存储在$Pictures_Size_MB)的类型为System.String的,因此,比较运算符不能按预期工作。

尝试先做数学,然后格式化。像这样:

$Pictures_Size = (Get-ChildItem $User\Pictures -recurse | Measure-Object -property length -sum).sum 
if ($Pictures_Size -gt 1TB) { 
    # Output as double 
    [System.Math]::Round(($Pictures_Size/1TB), 2) 
    # Or output as string 
    "{0:N2} TB" -f ($Pictures_Size/1TB) 
} 
0

您正在使用字符串格式器,因此将您的变量值存储为字符串。删除不必要的"{0:N2} -f",而改为使用[Math]::Round()

相关问题