Capturing Powershell output in C# after Pipeline.Invoke throws

前端 未结 3 619
时光说笑
时光说笑 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:38

    I have the same problem. The easiest way to get output when pipe.Invoke() throws an exception is to use Invoke(IEnumerable input, IList output)

    Example shows how to get all output, error, waning etc. in the correct order

    PowerShell script

    Write-Output "Hello world" 
    Write-Error "Some error"
    Write-Warning "Some warning"
    throw "Some exception"
    

    C#

    List RunLog = new List(); 
    
    using (System.Management.Automation.PowerShell psInstance = System.Management.Automation.PowerShell.Create())
    
    {
        psInstance.AddScript(_Script);
    
    psInstance.Streams.Error.DataAdded += (sender, args) =>
    {
        ErrorRecord err = ((PSDataCollection)sender)[args.Index];
        RunLog.Add($"ERROR: {err}");
    };
    
    psInstance.Streams.Warning.DataAdded += (sender, args) =>
    {
        WarningRecord warning = ((PSDataCollection)sender)[args.Index];
        RunLog.Add($"WARNING: {warning}");
    };
    
    ... etc ...
    
    var result = new PSDataCollection();
    result.DataAdded += (sender, args) =>
    {
        PSObject output = ((PSDataCollection)sender)[args.Index];
        RunLog.Add($"OUTPUT: {output}");
    };
    
    try
    {
        psInstance.Invoke(null, result);
    }
    catch(Exception ex)
    {
        RunLog.Add($"EXCEPTION: {ex.Message}");
    }                                                
    }
    

提交回复
热议问题