目录大小错误

时间:2012-02-14 19:12:47

标签: powershell directory

我有一个脚本来检查文件夹及其所有子文件夹的大小,它可以满足我的需要,但如果文件夹的大小为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"
}

3 个答案:

答案 0 :(得分:3)

最后我明白了。当一个文件夹没有文件时,即使它有非空文件夹,也会发生错误。 EBGreen发布的解决方案不完整,因为它只考虑子文件。

正确的脚本是:

$folder = $args[0]
[console]::WriteLine($folder)
$startFolder = $folder

#here we need the size of all subfiles and subfolders. Notice the -Recurse
$colItems = (Get-ChildItem $startFolder -Recurse | Measure-Object -property length -sum)
"$startFolder -- " + "{0:N2}" -f ($colItems.sum / 1MB) + " MB"
"------"

#here we take only the first level subfolders. Notice the Where-Object clause and NO -Recurse
$colItems = (Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object)
foreach ($i in $colItems)
    {
        $i.FullName
        #here we need again the size of all subfiles and subfolders, notice the -Recurse
        $subFolderItems = (Get-ChildItem $i.FullName -Recurse | Measure-Object -property length -sum)
        "                                   -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
    }

现在没有错误,值也很准确。

答案 1 :(得分:2)

这对我有用而没有错误:

$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 -ErrorAction SilentlyContinue)
    $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
}

答案 2 :(得分:0)

问题是Get-ChildItem的输出对于空文件夹是$ null。 Measure-Object期望具有长度属性的输入对象。所以你可以省略对文件夹的处理是空的,如下所示:

foreach ($i in $colItems)
{
    if ($i.GetFileSystemInfos().Count) {
        $subFolderItems = (Get-ChildItem $i.FullName | Measure-Object -property length -sum)
        $i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB"
    }
}