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"
}
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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With