4

Problem: powershell script stops because of an exception which should be caught by the try block when using $ErrorActionPreference

Example:

$ErrorActionPreference = 'Stop'
try {
    ThisCommandWillThrowAnException
} catch {
    Write-Error 'Caught an Exception'
}
# this line is not executed. 
Write-Output 'Continuing execution'  
Cœur
  • 37,241
  • 25
  • 195
  • 267
Vlad Nestorov
  • 330
  • 2
  • 9

1 Answers1

6

Solution: Write-Error actually throws a non-terminating exception by default. When $ErrorActionPreference = 'Stop' is set, Write-Error throws a terminating exception within the catch block.

Override this using -ErrorAction 'Continue'

$ErrorActionPreference = 'Stop'
try {
    ThisCommandWillThrowAnException
} catch {
    Write-Error 'Caught an Exception' -ErrorAction 'Continue'
}
# this line is now executed as expected
Write-Output 'Continuing execution' 
Vlad Nestorov
  • 330
  • 2
  • 9