I have short C# code which fires an invalid command using powershell.
using (PowerShell PowerShellInst = PowerShell.Create())
{
PowerShellInst.AddScript("abc");
Collection<PSObject> PSOutput = PowerShellInst.Invoke();
Console.WriteLine(PSOutput);
}
Output is not printing anything. when same command fire using actual powershell then following output is printed.

How can I get error output in C sharp code?
To get the errors, you can check if the powershell object HadError then look into Streams.Error property of the powershell object and for each ErrorRecord, you can get the Exception, StackTrace, ToString, etc:
using (var powerShell = PowerShell.Create())
{
var output = powerShell.AddScript("abc").Invoke();
if(powerShell.HadErrors)
{
foreach(var error in powerShell.Streams.Error)
{
Console.WriteLine(error.ToString());
}
}
}
Note: PowerShell provides multiple streams for different purposes: Debug, Error, Information, Progress, Verbose, Warning. You can get the streams using Streams property of your powershell instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With