Capturing Powershell output in C# after Pipeline.Invoke throws

前端 未结 3 622
时光说笑
时光说笑 2020-12-03 15:14

I\'m running a Powershell test script from a C# application. The script can fail due to a bad cmdlet which causes pipe.Invoke() to throw an exception.

I\'m able to c

3条回答
  •  情话喂你
    2020-12-03 15:48

    Not sure if this is helpful. I am guessing you are running V1. This V2 approach doesn't throw and prints the result:

    Hello World
    67 errors
    
    string script = @"
      'Hello World'
      ps | % {
        $_.name | out-string1
      }
    ";
    
    PowerShell powerShell = PowerShell.Create();
    
    powerShell.AddScript(script);
    var results = powerShell.Invoke();
    
    foreach (var item in results)
    {
      Console.WriteLine(item);
    }
    
    if (powerShell.Streams.Error.Count > 0)
    {
      Console.WriteLine("{0} errors", powerShell.Streams.Error.Count);
    }
    

提交回复
热议问题