 <p>You're getting an exception from the DirectoryInfo object, so you need to use try / catch:</p> <pre><code>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 } </code></pre> <p>If you're getting errors from any powershell cmdlets, you can use <code>-ErrorAction SilentlyContinue</code> on the cmdlet to prevent errors printing to the screen.</p>