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
  • 34,719
  • 24
  • 185
  • 251
Vlad Nestorov
  • 300
  • 1
  • 9

1 Answers1

3

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
  • 300
  • 1
  • 9