Question

Ive found a useful powershell script on this site with a function for counting files/folder sizes.

Im using this because it is fast and low memory use for large files/folders.

The problems is that when it encounters a folder it doesn't have access to I get output to the console saying access denied.

Exception calling "GetFiles" with "0" argument(s): "Access to the path 'c:\users\administrator\AppData\Local\Applicati\
n Data' is denied."
At line:4 char:37
+         foreach ($f in $dir.GetFiles <<<< ())
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I know, or think I need to use |Out-Null to suppress the errors, but still have the script work, however I just cannot figure out where or how to do this, despite multiple attempts.

So heres the script if anyone has any ideas?

function Get-HugeDirStats ($directory) {
    function go($dir, $stats)
    {
        foreach ($f in $dir.GetFiles())
        {
            $stats.Count++ 
            $stats.Size += $f.Length
        } 
        foreach ($d in $dir.GetDirectories())
        {
            go $d $stats
        } 
    }
    $statistics = New-Object PsObject -Property @{Count = 0; Size = [long]0 }
    go (new-object IO.DirectoryInfo $directory) $statistics
    $statistics
}
$stats = Get-HugeDirStats c:\users
Was it helpful?

Solution

You're getting an exception from the DirectoryInfo object, so you need to use try / catch:

function Get-HugeDirStats ($directory) {
    function go($dir, $stats)
    {
        try {
            foreach ($f in $dir.GetFiles())
            {
                $stats.Count++ 
                $stats.Size += $f.Length
            } 
            foreach ($d in $dir.GetDirectories())
            {
                go $d $stats
            }
        } 
        catch [Exception] {
            # Do something here if you need to
        }
    }
    $statistics = New-Object PsObject -Property @{Count = 0; Size = [long]0 }
    go (new-object IO.DirectoryInfo $directory) $statistics
    $statistics
}

If you're getting errors from any powershell cmdlets, you can use -ErrorAction SilentlyContinue on the cmdlet to prevent errors printing to the screen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top