3

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?

2
  • What is abc referring to? Commented Jan 9, 2021 at 12:55
  • 1
    this is just an invalid command, on runtime I am executing an exe file with full path , but it can happen that exe is not there. so wanted to print error Commented Jan 9, 2021 at 12:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.