Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory size error

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"
}
like image 710
jfingers Avatar asked May 29 '26 20:05

jfingers


2 Answers

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:

$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"
    }

Now there's no error and the values are accurate.

like image 67
AndreiM Avatar answered May 31 '26 18:05

AndreiM


this worked for me without errors:

$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"
}
like image 20
EBGreen Avatar answered May 31 '26 17:05

EBGreen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!