How to handle errors for the commands to run in Start-Job?

后端 未结 1 869
说谎
说谎 2021-01-25 18:55

I am writing an automation script. I had a function which takes either a command or an executable. I had to wait until the command or executable has completed running and return

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 19:39

    When in doubt, read the documentation:

    $?
    Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

    […]

    $LASTEXITCODE
    Contains the exit code of the last Windows-based program that was run.

    Basically, you need to check both. $? indicates whether the last PowerShell command/cmdlet was run successfully, whereas $LASTEXITCODE contains the exit code of the external program that was last executed.

    if (-not $? -or $LASTEXITCODE -ne 0) {
        throw '... whatever ...'
    } else {
        return $ret
    }
    

    However, Invoke-Expression is not a very good approach to executing commands. Depending on what you actually want to execute there are probably better ways to do it, with better methods for error handling.

    0 讨论(0)
提交回复
热议问题