在 C# 中获取 Powershell 脚本的错误并使用条件语句输出它?

Getting the error of a Powershell Script within c# and outputting it with conditional statement?

我有一个控制台应用程序和一个在控制台应用程序中执行 PowerShell 脚本的方法。所以我试图获取它在应用程序中输出的错误文本并对其进行处理。

Example/What 我正在尝试:

    If Error.contains("Object") 
{
    // do something here
}

这是我目前的方法

  public void ExecutePowershellScript()
{
  var file = @"C:\Path\filename.ps1";
           
            var start = new ProcessStartInfo()
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
                UseShellExecute = false
            };
            Process.Start(start);
}

您可以设置 RedirectStandardError = true 并访问 process.StandardError

中的任何错误
    public static void ExecutePowershellScript()
    {
        var file = @"C:\Path\filename.ps1";

        var start = new ProcessStartInfo()
        {
            FileName = "powershell.exe",
            Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
        using Process process = Process.Start(start);
        string output = process.StandardOutput.ReadToEnd();
        string errors = process.StandardError.ReadToEnd();
    }



好吧,把上面的建议划掉。 经mklement0修正后,

This is a perfectly reasonable attempt, but, unfortunately, it can lead to hangs (while waiting for one's stream end, the other, when exceeding the buffer size, may cause process execution to block). If you need to capture both streams, you must collect the output from one of them via events. – mklement0

我更改了使用 ErrorDataReceived 事件的解决方案

        public static async Task ExecutePowershellScript()
        {
            var file = @"C:\Path\filename.ps1";

            var start = new ProcessStartInfo
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
                UseShellExecute = false,
                // redirect standard error stream to process.StandardError
                RedirectStandardError = true
            };

            using var process = new Process
            {
                StartInfo = start
            };

            // Subscribe to ErrorDataReceived event
            process.ErrorDataReceived += (sender, e) =>
            {
                //  code to process the error lines in e.Data
            };

            process.Start();

            // Necessary to start redirecting errors to StandardError
            process.BeginErrorReadLine();

            // Wait for process to exit
            await process.WaitForExitAsync();

        }
start.Start();
while (!start.StandardOutput.EndOfStream)
{
    string line = start.StandardOutput.ReadLine();
}

Process.start: how to get the output?

当您创建 Process 对象时,适当地设置 StartInfo:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

然后启动进程并从中读取:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

您可以使用 int.Parse() 或 int.TryParse() 将字符串转换为数值。如果您读取的字符串中存在无效数字字符,您可能需要先进行一些字符串操作。