如何通过文件夹递归并确定文件夹大小?

时间:2012-06-13 07:24:50

标签: windows powershell directory powershell-v2.0

我在“Windows PowerShell Tip of the Week”中提供了稍微修改过的脚本版本。我们的想法是确定文件夹及其子文件夹的大小:

$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

出现此错误的原因是什么以及如何优化脚本以克服?

2 个答案:

答案 0 :(得分:4)

您可以使用-ErrorAction的{​​{1}}参数:

Measure-Object

或其别名$subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum -ErrorAction SilentlyContinue) ,带有数值,非常适合在交互式实验中快速添加它:

-ea

根据我的拙见,Technet上的脚本是非常糟糕的PowerShell代码。

作为一种非常快速和肮脏(和缓慢)的解决方案,您还可以使用以下单行:

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

或者实际上是单行:

# 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

答案 1 :(得分:-1)

我在Windows 7上运行它,它可以工作(剪切和粘贴你的代码)。也许你的路上有一个“名不好”的文件?