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

落爺英雄遲暮 提交于 2019-12-20 05:29:07

问题


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 if failed or passed. I also want to write the output to file. I am trying with the Start-Job cmdlet.

My current code:

$job = Start-Job -scriptblock {
    Param($incmd)
    $ret = Invoke-Expression $incmd -ErrorVariable e
    if ($e) {
        throw $e
    } else {
        return $ret
    }
} -ArumentList $outcmd

Wait-Job $job.id

"write the output to file using receive-job and return if passed or failed"

This works perfectly fine for commands but for executables irrespective of errorcode the value of $e is null. This falsely shows as passed even though the errorcode is 0.

I tried with errorcode using $LASTEXISTCODE and $?. But $? is true for executables and $LASTEXISTCODE is either null or garbage value for commands. I am out of ideas and struck here.


回答1:


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.



来源:https://stackoverflow.com/questions/45738707/how-to-handle-errors-for-the-commands-to-run-in-start-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!