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
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}");
}
}