2

「 WindowsPowerShellの今週のヒント」に示されているスクリプトのわずかに変更されたバージョンがあります。アイデアは、フォルダとそのサブフォルダのサイズを決定することです。

$startFolder = "C:\Temp\"

$colItems = (Get-ChildItem $startFolder | Measure-Object | Select-Object -ExpandProperty count)
"$startFolder -- " + "{0:N2}" -f ($colItems.sum / 1MB) + " MB"

$colItems = (Get-ChildItem $startFolder -recurse | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems)
    {
        $subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum)
        $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
    }

このスクリプトは正常に実行されますが、特定のフォルダーで次のようなエラーが発生します。

Measure-Object : Property "length" cannot be found in any object(s) input.
At line:10 char:70
+         $subFolderItems = (Get-ChildItem $i.FullName | Measure-Object <<<<  -property length -sum)
    + CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException
    + FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand

このエラーの理由と、克服するためにスクリプトを改良する方法は何ですか?

4

2 に答える 2

4

-ErrorAction次のパラメータを使用できますMeasure-Object

$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum -ErrorAction SilentlyContinue)

-eaまたは、数値を含むそのエイリアス。インタラクティブな実験ですばやく追加するのに便利です。

$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum -ea 0)

私の謙虚な意見では、Technetのスクリプトは非常に貧弱なPowerShellコードです。

非常に速くて汚い(そして遅い)解決策として、次のワンライナーを使用することもできます:

# Find folders
Get-ChildItem -Recurse | Where-Object { $_.PSIsContainer } |
# Find cumulative size of the directories and put it into nice objects
ForEach-Object {
    New-Object PSObject -Property @{
        Path = $_.FullName
        Size = [Math]::Round((Get-ChildItem -Recurse $_.FullName | Measure-Object Length -Sum -ErrorAction SilentlyContinue).Sum / 1MB, 2)
    }
} |
# Exclude empty directories
Where-Object { $_.Size -gt 0 } |
# Format nicely
Format-Table -AutoSize

または実際にはワンライナーとして:

gci -r|?{$_.PSIsContainer}|%{New-Object PSObject -p @{Path=$_.FullName;Size=[Math]::Round((gci -r $_.FullName|measure Length -s -ea 0).Sum/1MB,2)}}|?{$_.Size}|ft -a
于 2012-06-13T08:59:37.463 に答える
-1

私はそれをWindows7で実行しています、そしてそれは動作します(あなたのコードを切り取って貼り付けます)。たぶんあなたのパスに「良くない名前」のファイルがありますか?

于 2012-06-13T08:42:22.393 に答える