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

前端 未结 3 500
傲寒
傲寒 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 16:50

    Try-Catch will catch an exception and allow you to handle it, and perhaps handling it means to stop execution... but it won't do that implicitly. It will actually consume the exception, unless you rethrow it. But your issue is simpler than that -- the try block takes precedence over the -ErrorAction stop in your get-content cmdlet. So instead of stopping execution, you get taken to the Catch block and continue on because there is no error handling in the catch block.

    Try removing the try-catch logic from your script, and allow the cmdlet to error out:

    get-content "c:\GarbageFileName.txt" -ErrorAction stop
    write-output "You won't reach me if GarbageFileName doesn't exist."
    

    And you should get the desired result of execution not reaching write-output:

    PS C:\> .\so-test.ps1
    Get-Content : Cannot find path 'C:\GarbageFileName.txt' because it does not exist.
    At C:\so-test.ps1:2 char:12
    + get-content <<<<  "c:\GarbageFileName.txt" -ErrorAction stop
        + CategoryInfo          : ObjectNotFound: (C:\GarbageFileName.txt:String) [Get-Content], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
    

提交回复
热议问题