c# - 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的返回值?
解决方案
你可以使用这个:
$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 以写入控制台,那么您所做的将起作用。
推荐阅读
- node.js - Webpack 在我的 node.js 项目中不起作用。事件
- c# - 我应该如何通过c#编程在word文档中插入动态雷达图
- android - 如果设备未植根,则以编程方式完成时,安装对话框不会在 oreo 中显示
- c# - 数据未插入表中,如果我们选择多个材料和数量,此 DAL 函数会多次调用
- javascript - 反应 - 将状态传递给父组件 - 过多的 AXIOS 请求
- c# - 来自 WebAPI 控制器的 Signalr 集线器连接
- javascript - 在对象的创建和执行阶段发生了什么?
- python - 在 Python 2.7 中通过“target =”与“args =”将参数传递给线程
- c# - 文化不敏感 VS 文化敏感
- html - 在可滚动菜单栏上完全显示工具提示的解决方案