The script I'm writing frequently tries to delete files it doesn't have the ability to. This throws some errors, one where it doesn't have sufficient access rights and another where it later tries to delete the non-empty folder containing the first issue. It's fine that these hang around, but I'd like to still output error messages if anything is every thrown that isn't one of those two messages.
A try-catch block isn't catching anything, as they're errors rather than exceptions.
try
{
Remove-Item D:\backup\* -Recurse
Write-Host "Success" -ForegroundColor Green
Write-Host $error.count
}
catch
{
Write-Host "caught!" -ForegroundColor Cyan
}
Even though $error.count has errors inside it, it still successfully completes the try-block. Am I forced to manually check to see whether there's anything new in $error each time, or is there a better way for doing this? Thanks!