ExitCode 始终为 null 不显示来自 exe 的实际 return 值

ExitCode always has null does not show the actual return value from exe

我正在从 powershell 脚本调用我的 exe,如下所示。

$file = $PSScriptRoot + "\executor.exe"
$code = (Start-Process -WindowStyle Hidden $file -Verb runAs -ArgumentList $Logfile).StandardOutput.ToString;
$nid = (Get-Process "executor.exe").id
Wait-Process -Id $nid

if ($code -eq 1) {
    LogWrite "Execution succeeded"
} else
{
    LogWrite "Execution Failed"
}

我的 exe 程序中有一个 int main 函数,它 return 成功时为 1,失败时为 0。 当我尝试从 powershell 脚本获取 ExitCode(使用 $LASTEXITCODE)时,它总是显示 null(既不是 1 也不是 0),但是我的 exe 是 returning 1,正如预期的那样。 如何在 powershell 脚本中捕获 exe 的 return 值?

你可以使用这个:

$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = # path to your exe file

# additional options:
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $false
$psi.WindowStyle = "Maximized"


$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.Start() | Out-Null # returns $true if the process started, $false otherwise
$p.WaitForExit()

# here's the exitcode
$exitCode = $p.ExitCode

创建进程启动信息,以指定可执行文件路径和其他选项。使用 .WaitForExit() 等待过程完成很重要。

您所尝试的并没有获得应用程序退出代码,而是应用程序写入标准控制台的内容,在您的情况下,我认为这没什么。如果您可以修改 exe 以写入控制台,那么您所做的就可以了。