Search code examples
powershelldirectorysize

The size folder returns 0


I have script:

$array = @("c:")

    foreach ($z in $array) 
        {
            
            $FileSystemObject = New-Object -com  Scripting.FileSystemObject
            $folders = (Get-Childitem $z | ? {$_.Attributes -eq "Directory"})

            foreach ($folder in $folders)
                {
                  Write-Host "Counting for..." "$folder "
                  $FileSystemObject.GetFolder($folder.FullName).Size/1GB                            
                }
        }

As a result, I get something like this:

Counting for... Programs 0,0629891464486718

Counting for... Pictures_temp 1,2558867437765

Counting for... temp 13,7048118021339

Counting for... Windows 0

I don't know why I didn't get the "Program Files" or "Users" folders, for example (permission problem? I have admin rights). And why Windows returns 0. Treats system folders differently, I suppose. But is there any way to solve it? The same thing happens with some of my network folders and I get wrong data.


Solution

  • I do have consistent result with this. Pay attention it outputs errors in case of access denied to child items. Run as admin or either handle $error to discard those properly.

    $array = @("c:")
    foreach ($z in $array) 
    {   Get-Childitem $z | Where-Object { $_.PSIsContainer } | ForEach-Object {
            Write-Host "  for..." "$_"
            ((Get-ChildItem $_.FullName -Recurse | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum)/1Gb
        }
    }
    

    or, to respect initial script

    $array = @("c:")
    foreach ($z in $array) 
    {   $folders = (Get-Childitem $z | Where-Object { $_.PSIsContainer })
        $folders | ForEach-Object {
            Write-Host "  for..." "$_"
            ((Get-ChildItem $_.FullName -Recurse | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum)/1Gb
        }
        Clear-variable -name folders -ErrorAction SilentlyContinue
    }