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.