Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Invoke invalid command output C#

Tags:

c#

powershell

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.

enter image description here

How can I get error output in C sharp code?

like image 780
max Avatar asked Sep 25 '26 11:09

max


1 Answers

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.

like image 54
Reza Aghaei Avatar answered Sep 27 '26 01:09

Reza Aghaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!