1

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!

2 Answers 2

2

In a Try/Catch, the Catch block is only invoked on terminating errors.

Use the ErrorAction common parameter to force all errors to be terminating:

try
{
    Remove-Item D:\backup\* -Recurse -ErrorAction Stop
    Write-Host "Success" -ForegroundColor Green
    Write-Host $error.count
}
catch
{
    Write-Host "caught!" -ForegroundColor Cyan
}
Sign up to request clarification or add additional context in comments.

Comments

0

Or use a global erroraction:

try {
 $erroractionpreference = 'stop'
 Remove-Item D:\backup\* -Recurse 
 Write-Host "Success" -ForegroundColor Green
 Write-Host $error.count 
} catch { 
 Write-Host "caught!" -ForegroundColor Cyan
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.