如何处理要在Start-Job中运行的命令的错误? [英] How to handle errors for the commands to run in Start-Job?

查看:168
本文介绍了如何处理要在Start-Job中运行的命令的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个自动化脚本。我有一个需要命令或可执行文件的函数。我必须等到命令或可执行文件完成运行,如果失败或通过则返回。我也想将输出写入文件。我正在尝试使用 Start-Job cmdlet。

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.

我当前的代码:

$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"

这对于命令非常有用,但对于可执行文件,无论错误代码如何, $ e 的值为空。即使错误代码为0,也会错误地显示为已通过。

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.

我尝试使用 $ LASTEXISTCODE $?。但是 $?对于可执行文件是正确的,而 $ LASTEXISTCODE 对于命令来说是null或垃圾值。我没主意,就被打到这里。

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.

推荐答案

如有疑问,请阅读文档


$?

包含上一个操作的执行状态。如果上一次操作成功,则包含TRUE;如果失败,则包含FALSE。

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

[…]

[…]

$ LASTEXITCODE

包含运行的最后一个基于Windows的程序的退出代码。

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

基本上,您需要同时检查两者。 $?指示是否成功运行了最后一个 PowerShell 命令/ cmdlet,而 $ LASTEXITCODE 包含最后执行的外部程序的退出代码。

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
}

但是, Invoke-Expression 不是执行命令的很好方法。根据您实际要执行的操作,可能有更好的方法以及更好的错误处理方法。

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.

这篇关于如何处理要在Start-Job中运行的命令的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆