I\'m trying to get my script to stop if it hits an error, and use try... catch to give me an easy way to handle the error. The easiest thing in the world I\'d have thought,
The only thing missing is your break
-statement in the Catch-block. Powershell won't stop the script if you don't instruct it to.
try {
get-content "c:\GarbageFileName.txt" -ErrorAction stop
}
catch {
write-output "in catch, I want it to stop now"
break
}
write-output "try-catch finished, script is continuing"
And a small addendum, in case it helps you: with finally
, you can add some lines of code that are always executed, regardless of wether an exception was thrown or not.
try {
get-content "c:\GarbageFileName.txt" -ErrorAction stop
}
catch {
write-output "in catch, I want it to stop now"
break
}
finally {
#do some stuff here that is executed even after the break-statement, for example:
Set-Content -Path "f:\GarbageFileName.txt" -Value $null
}
#the line below is executed only if the error didn't happen
write-output "try-catch finished, script is continuing"