目录大小错误
我有一个脚本来检查文件夹及其所有子文件夹的大小,它可以满足我的需要,但如果文件夹大小为 0,它会抛出错误。我想添加一些逻辑,但我似乎找不到好方法,提前感谢您的帮助。
脚本是:
$startFolder = "C:\"
$colItems = (Get-ChildItem $startFolder | Measure-Object -property length -sum)
"$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"
}
I have a script to check the size of a folder and all of its sub-folders and it does what I need but it throws errors if the folder has size 0. I would like to add some logic in but I cant seem to find a good way to do it, thanks in advance for the help.
The script is:
$startFolder = "C:\"
$colItems = (Get-ChildItem $startFolder | Measure-Object -property length -sum)
"$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"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最后我得到了这个。当一个文件夹没有文件时,即使它有非空文件夹,也会发生此错误。 EBGreen 发布的解决方案并不完整,因为它只考虑了子文件。
正确的脚本是:
现在没有错误并且值是准确的。
Finally I got this. The error happens when one folder has no file, even if it has non-empty folders. The solution posted by EBGreen is incomplete, because it takes only sub-files into consideration.
The correct script is:
Now there's no error and the values are accurate.
这对我有用,没有错误:
this worked for me without errors:
问题在于,对于空文件夹,
Get-ChildItem
的输出为 $null。 Measure-Object 需要一个具有长度属性的输入对象。因此,您可以省略对空文件夹的处理,如下所示:The issue is that the output of
Get-ChildItem
is $null for empty folders. Measure-Object is expecting an input object with a property of length. So you can just omit that processing for folders are empty like this: