Powershell 脚本不在控制台上显示任何输出

问题描述 投票:0回答:1

我有下面的代码片段,它从后端的 c# 文件运行。

using (Process process = new Process())
                {
                    process.StartInfo.FileName = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
                    String cmd = "C:\\Users\\xyz\\AppData\\Local\\Temp\\2\\Demo.ps1";
                    process.StartInfo.Arguments = cmd;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = false;
                    process.StartInfo.RedirectStandardError = true;
                    StringBuilder error = new StringBuilder();

                    process.Start();

                    while (true)
                    {
                        bool hasExited = process.HasExited;

                        String errorStr = null;
                        while ((errorStr = process.StandardError.ReadLine()) != null)
                            error.AppendLine(errorStr);

                        if (hasExited)
                            break;

                        Thread.Sleep(100);
                    }

                    if (process.ExitCode != 0 || error.Length > 0)
                        throw new Exception(error.ToString());
                }

演示.ps1

write-host "Working Properly now ! "

我希望将字符串打印在打开的同一个 powershell 窗口上,但不知何故它没有显示任何输出到打开的 powershell 窗口。如果我将输出重定向到文本文件,那么它就清晰可见

c# powershell scripting
1个回答
0
投票

您观察到的行为是因为您将 PowerShell 作为具有不同输入和输出流的单独进程运行,并且 PowerShell 脚本生成的输出不会自动显示在父控制台窗口中。当您以这种方式运行 PowerShell 时,如果您想在父控制台中看到输出,则需要显式处理输出的重定向。

删除这一行 process.StartInfo.RedirectStandardOutput = false;从你的代码。此行告诉进程不要重定向标准输出。

修改 Demo.ps1 脚本以使用 Write-Output cmdlet 而不是 Write-Host。

Write-Output "Working Properly now !"

修改代码

using (Process process = new Process())
{
    process.StartInfo.FileName = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
    String cmd = "C:\\Users\\xyz\\AppData\\Local\\Temp\\2\\Demo.ps1";
    process.StartInfo.Arguments = cmd;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardError = true;
    StringBuilder error = new StringBuilder();

    process.Start();

    while (true)
    {
        bool hasExited = process.HasExited;

        String errorStr = null;
        while ((errorStr = process.StandardError.ReadLine()) != null)
            error.AppendLine(errorStr);

        if (hasExited)
            break;

        Thread.Sleep(100);
    }

    if (process.ExitCode != 0 || error.Length > 0)
        throw new Exception(error.ToString());
}
© www.soinside.com 2019 - 2024. All rights reserved.