2017-08-30 288 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()

相關問題