【问题标题】:Get ExitCode from Process in PowerShell While Redirecting StandardError重定向 StandardError 时从 PowerShell 中的进程获取 ExitCode
【发布时间】:2018-01-17 20:41:58
【问题描述】:

我目前正在编写包含该行的 PowerShell 脚本

$process1 = Start-Process -FilePath ($exePath1) -PassThru -RedirectStandardError ($logPath1)

这会启动一个长时间运行的进程并将进程的 StandardError 重定向到日志文件。我的问题是这显然也会干扰 ExitCode。

$process1.ExitCode

在进程退出后返回 null。如果我删除“RedirectStandardError ($logPath1)”然后 ExitCode 返回我的虚拟程序应该返回的值。

我应该做一些不同的事情吗?我希望能够启动该过程(将 StandardError 重定向到日志文件以进行诊断),等待几秒钟以确保它不会崩溃,并在它崩溃时检索 ErrorCode。

【问题讨论】:

  • 在获取$process1.ExitCode之前先使用$process1.WaitForExit()
  • @t0mm13b:我正在使用 $process1.HasExited。有问题的进程很容易受到配置错误的影响,所以我想启动它并确保它没有崩溃。

标签: powershell exit-code


【解决方案1】:

如果您需要等待进程并且您没有以其他用户身份运行它:

$StartParams = @{
    FilePath = $exePath1
    RedirectStandardError = $logPath1
    PassThru = $True
    Wait = $True
}
$ReturnCode = (Start-Process @StartParams).ExitCode

由于它是长期运行的,这里有一个 PSJobs 的替代方法:

$Job = Start-Job -ScriptBlock {
    $StartParams = @{
        FilePath = $exePath1
        RedirectStandardError = $logPath1
        PassThru = $True
        Wait = $True
    }
    (Start-Process @StartParams).ExitCode
}
If ($Job.State -eq 'Completed')
{
    $ReturnCode = Receive-Job -Job $Job
}

【讨论】:

  • 赞成“等待”的想法,但不幸的是,这对我不起作用,因为有问题的过程是长期存在的;我不能让我的脚本挂起等待它可能出错。
  • 然后启动子脚本作为一项工作来完成这项工作?
  • 这部分有效,尽管行为是......奇怪。首先,您不能从外部范围访问变量,所以我必须将它们传递进去。现在它启动了我的控制台应用程序,但即使在 Flush 上也没有输出写入控制台。我知道它正在工作,但没有显示任何内容。最奇怪的是,即使包含 -Wait,$Job.State -eq 'Completed' 实际上返回 true。 $Job.Error 返回空值。有什么想法吗?
  • 哦,没错。确保包含 $using 范围,否则必须将它们作为参数传递。 @dornadigital 至于您的其他问题,您的控制台应用程序是否写入标准输出?可能想尝试启动一个新窗口。考虑到您尝试运行的方式,我认为您的 exe 是非交互式的。
  • 使用 $Job = Start-Job -ArgumentList $exePath1, $logPath1 -ScriptBlock { invoke-expression ("cmd /c start powershell -Command {(Start-Process -FilePath '" + $args[ 0] + "' -RedirectStandardError '" + $args[1] + "' -PassThru -Wait).ExitCode}") } 启动一切如我所料,但我似乎无法再次访问 ExitCode。 Receive-Job -Job $Job 只返回空值。这是速度和位置问题之一吗,你可以知道其中一个但不知道另一个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
相关资源
最近更新 更多