首页 > 解决方案 > ExitCode 总是有 null 不显示 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 函数,成功时返回 1,失败时返回 0。当我尝试从 powershell 脚本获取 ExitCode(使用 $LASTEXITCODE)时,它总是显示 null(既不是 1 也不是 0),但我的 exe 按预期返回 1。如何在powershell脚本中捕获exe的返回值?

标签: c#powershellreturnreturn-value

解决方案


你可以使用这个:

$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 以写入控制台,那么您所做的将起作用。


推荐阅读