You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从C#调用PowerShell脚本无法获取退出码求助

解决C#调用PowerShell脚本获取退出码及Invoke返回空的问题

问题原因分析

  1. Invoke返回PSObject计数为0:你的PowerShell脚本使用Write-Host输出内容,Write-Host的输出直接发送到主机控制台,不会进入PowerShell的输出管道,因此ps.Invoke()无法捕获到这些内容。
  2. 无法获取退出码:当前代码未正确读取PowerShell执行后的退出状态信息,需要通过PowerShell实例的特定属性获取。

修正方案

1. 修改PowerShell脚本

将Write-Host改为Write-Output(或直接输出字符串),让内容进入输出管道,这样Invoke()就能捕获到:

Start-Sleep -Seconds 30

Write-Output "Exit code is : 25"

exit 25

2. 修改C#代码

  • 修复语法错误:ps.Dispose;改为ps.Dispose();,确保脚本路径为合法字符串
  • 通过ps.InvocationStateInfo.ExitCode获取脚本退出码
  • 可通过ps.Streams.Error检查执行过程中的错误

修改后的C#代码:

using (PowerShell ps = PowerShell.Create())
{
    // 传入正确的脚本路径字符串
    ps.AddScript(File.ReadAllText("buildScript.ps1"));       
    var psResults = ps.Invoke();

    // 处理捕获到的管道输出
    foreach (PSObject psObj in psResults)
    {
        var result = psObj.ToString();
        Console.WriteLine(result);
    }

    // 获取脚本退出码
    int exitCode = ps.InvocationStateInfo.ExitCode;
    Console.WriteLine($"脚本退出码:{exitCode}");

    // 检查执行过程中是否有错误
    if (ps.Streams.Error.Count > 0)
    {
        foreach (var error in ps.Streams.Error)
        {
            Console.WriteLine($"执行错误:{error.ToString()}");
        }
    }

    ps.Dispose();
}

额外说明

  • 若无需捕获脚本输出,仅需获取退出码,即使ps.Invoke()返回空,也能正常读取ExitCode属性
  • 若脚本因异常提前终止,ExitCode会反映错误状态,同时ps.HadErrors会返回true

内容的提问来源于stack exchange,提问作者BrandonE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:53:10