The following code tries to copy the file test in three different ways, using two functions with different error management techniques:
One of the two functions manages the errors with try/catch and is able to detect the first two errors, the other uses -ErrorAction and is able to detect the third error.
Is there one technique to catch all the errors?
Or do I always need to use both techniques?
function TestTryCatch($N, $Source, $Dest) {
Write-Output "$N TestTryCatch $Source $Dest"
try {Copy-Item $Source $Dest}
catch {Write-Output "Error: $($error[0].exception.message)"}
}
function TestErrorAction($N, $Source, $Dest) {
Write-Output "$N TestErrorAction $Source $Dest"
Copy-Item $Source $Dest -ErrorAction SilentlyContinue
if(!$?) {Write-Output "Error: $($error[0].exception.message)"}
}
New-Item 'test' -ItemType File | Out-Null
(New-Item 'hidden' -ItemType File).Attributes = 'Hidden'
TestTryCatch 1 'test' 'test'
TestTryCatch 2 'test' 'hidden'
TestTryCatch 3 'test' 'nonexistingfolder\test'
TestErrorAction 1 'test' 'test'
TestErrorAction 2 'test' 'hidden'
TestErrorAction 3 'test' 'nonexistingfolder\test'
Remove-Item 'test'
Remove-Item 'hidden' -Force
Your first version should work to catch all errors if you use -ErrorAction Stop like so:
function TestTryCatch($N, $Source, $Dest) {
Write-Output "$N TestTryCatch $Source $Dest"
try {Copy-Item $Source $Dest -ErrorAction Stop}
catch {Write-Output "Error: $($error[0].exception.message)"}
}
The key here is that Powershell differentiates between terminating and non-terminating errors, and non-terminating errors don't get caught by try {}. Using -ErrorAction Stop forces non-terminating errors to stop execution, and thus they get caught.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With