我在"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出现此错误的原因是什么?如何改进脚本以克服这些错误?
发布于 2012-06-13 16:59:37
您可以对Measure-Object使用-ErrorAction参数
$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-13 16:42:22
我在Windows 7上运行它,它可以工作(剪切和粘贴你的代码)。也许在你的路径中有一个带有“不好的名字”的文件?
https://stackoverflow.com/questions/11010035
复制相似问题