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

如何在PowerShell中获取C# .NET Framework控制台应用的返回值(支持布尔/字符串类型)

解决C#控制台应用与PowerShell交互的返回值问题

Let's work through your issues step by step:


1. 为什么StandardOutput读不到内容?

核心原因是你的C#控制台程序没有向标准输出流写入任何内容——当前代码只通过Main方法的返回值设置了ExitCode,但ExitCode和StandardOutput是完全独立的两个机制。

要让PowerShell能通过StandardOutput读取内容,你需要在C#代码里显式使用Console.WriteLine()(或Console.Write())来输出数据。


2. 如何返回布尔值/字符串类型的结果?

Windows进程的ExitCode只能是整数类型,所以如果要返回布尔值、字符串这类非整数数据,必须通过**标准输出流(StandardOutput)**来传递。下面是具体实现方案:

方案1:返回字符串类型

修改你的C#代码,在需要返回结果时向控制台输出字符串:

namespace PlainConsoleApp {
    class Program {
        static int Main(string[] args) {
            string result = string.Empty;
            switch (args[0]) {
                case "one":
                    result = "Success: Got argument 'one'";
                    // 正常退出设置0
                    return 0;
                case "two":
                    result = "Success: Got argument 'two'";
                    return 0;
                default:
                    result = "Error: Invalid argument";
                    // 错误退出设置非0
                    return -1;
            }
            // 关键:把结果写入标准输出
            Console.WriteLine(result);
        }
    }
}

对应的PowerShell脚本可以直接读取StandardOutput得到字符串:

$consoleApp = "C:\Temp\PlainConsoleApp.exe"
$arg1 = "one"

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $consoleApp
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $arg1

$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
# 注意:先读取输出再等待退出,避免缓冲区溢出导致程序挂起
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$p.WaitForExit()

Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: $($p.ExitCode)"

# 去除换行符后直接使用返回的字符串
$returnedString = $stdout.Trim()

方案2:返回布尔值

在C#里输出布尔值的字符串形式,再在PowerShell里转换为布尔类型:

namespace PlainConsoleApp {
    class Program {
        static int Main(string[] args) {
            bool isValid = false;
            switch (args[0]) {
                case "one":
                case "two":
                    isValid = true;
                    return 0;
                default:
                    isValid = false;
                    return -1;
            }
            Console.WriteLine(isValid);
        }
    }
}

PowerShell脚本中转换类型:

# 读取后转换为布尔类型
$returnedBool = [bool]$stdout.Trim()
Write-Host "Returned boolean value: $returnedBool"

额外注意事项

  • 读取输出的顺序:建议先调用ReadToEnd()读取StandardOutput和StandardError,再调用WaitForExit(),避免因为输出缓冲区满导致程序挂起。
  • 错误信息处理:如果需要区分正常结果和错误信息,可以把错误内容写入Console.Error.WriteLine(),这样PowerShell可以通过StandardError单独读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:43:10