2017-08-14 60 views
0

我運行在PowerShell命令下面我得到錯誤:如果大小小於1KB,試圖計算每個驅動器中文件夾和文件的大小,然後以KB爲單位打印大小MB或GB
使用PowerShell每個驅動器中的所有文件夾和文件的打印大小

ls -Force | Add-Member -Force -Passthru -Type ScriptProperty -Name Length -Value {ls $this -Recurse -Force | Measure -Sum Length | Select -Expand Sum } | Sort-Object Length -Descending | Format-Table @{label="TotalSize (MB)";If ($_.Length -lt 1KB) {expression={[Math]::Truncate($_.Length/1KB)};width=14} else {expression={[Math]::Truncate($_.Length/1GB)};width=14}}, @{label="Mode";expression={$_.Mode};width=8}, Name 

錯誤

Missing '=' operator after key in hash literal. 
    At line:1 char:230 
    + ls -Force | Add-Member -Force -Passthru -Type ScriptProperty -Name 
    Length -Value {ls $this -Recurse -Force | Measure 
    Sum Length | Select -Expand Sum } | Sort-Object Length -Descending |   
    Format-Table @{label="TotalSize (MB)";If (<<<< $ 
    _.Length -lt 1KB) {expression={[Math]::Truncate($_.Length/
    1KB)};width=14} else {expression={[Math]::Truncate($_.Lengt 
    h/1GB)};width=14}}, @{label="Mode";expression={$_.Mode};width=8}, 
    Name 
    + CategoryInfo   : ParserError: (:) [], 
    ParentContainsErrorRecordException 
    + FullyQualifiedErrorId : MissingEqualsInHashLiteral 
+1

在'expression = {}'塊內移動'if/else' –

回答

1

由於錯誤信息提示時,你不能直接將任意值表達式中一個哈希表的文字。

移動狀態Expression腳本塊內:

@{ 
    label="TotalSize (MB)" 
    expression={ 
     if($_.Length -lt 1KB){ 
      [Math]::Truncate($_.Length/1KB) 
     } 
     else{ 
      [Math]::Truncate($_.Length/1GB) 
     } 
    } 
    width=14 
} 

雖然我認爲你應該刪除標籤的(MB)一部分在這種情況下,因爲你沒有真正顯示MB大小。

1

我建議使用幫助函數。

Function Get-FormattedBytes([decimal]$Bytes,[ValidateRange(0,15)]$Decimals=2){ 
    if ($Bytes -gt 1024PB){ return "$([Math]::Round(($Bytes/1024PB),$Decimals))EB" } 
    [email protected]('B','KB','MB','GB','TB','PB',"EB") 
    $Base = [Math]::Log($Bytes,1024);$Floor = [Math]::Floor($Base) 
    $Value=[Math]::Pow(1024,$Base-$Floor);$Suffix=$SufTable[$Floor] 
    return "$([Math]::Round($Value,$Decimals))$($Suffix)" 
} #handles up to 687 Billion Exabytes of data, should be enough... 

我把這一起放在一個不同的語言答案,但不記得提供信用的地方。

+0

最後一條評論:-P「640KB應該就足夠了......」 –

相關問題