How can I use try… catch and get my script to stop if there's an error?

前端 未结 3 479
傲寒
傲寒 2021-01-02 16:35

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,

3条回答
  •  再見小時候
    2021-01-02 17:04

    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"
    

提交回复
热议问题