Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read PowerShell exit code via c#

Tags:

c#

powershell

I am using System.Management.Automation.Runspaces to execute PowerShell scripts. is there an option i can read the exit code of a given script?

using System.IO;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Management.Automation;

namespace PowerShell
{
    public class PowerShellExecuter
    {
        public Collection<PSObject> RunPsScript(string psScriptFile)
        {
            string psScript;
            if (File.Exists(psScriptFile))
            {
                psScript = File.ReadAllText(psScriptFile);
            }
            else
            {
                throw new FileNotFoundException("Wrong path for the script file");
            }
            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.Open();

            RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);
            runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            Pipeline pipeLine = runSpace.CreatePipeline();
            pipeLine.Commands.AddScript(psScript);
            pipeLine.Commands.Add("Out-String");

            Collection<PSObject> returnObjects = pipeLine.Invoke();
            runSpace.Close();

            return returnObjects;
        }
    }
}
like image 849
user829174 Avatar asked Oct 15 '12 12:10

user829174


People also ask

How do I get the exit code in PowerShell?

Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script. It is in form of boolean values, with 0 for success and 1 for failure.

How do I navigate to C in PowerShell?

The Windows PowerShell prompt opens by default at the root of your user folder. Change to the root of C:\ by entering cd c:\ inside the Windows PowerShell prompt.

How do I know if a PowerShell script ran successfully?

You can use “$error” automatic variable. This will check if the first command throws error or if it completes successfully.


1 Answers

PowerShell commands have a richer error mechanism than integer exit codes. There is an error stream that non-terminating errors appear on. Terminating errors result in thrown exceptions so you need to handle those. The following code shows how to use the two mechanisms:

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;

namespace PowerShellRunspaceErrors
{
    class Program
    {
        private static PowerShell s_ps;

        static void Main(string[] args)
        {
            s_ps = PowerShell.Create();
            ExecuteScript(@"Get-ChildItem c:\xyzzy");
            ExecuteScript("throw 'Oops, I did it again.'");
        }

        static void ExecuteScript(string script)
        {
            try
            {
                s_ps.AddScript(script);
                Collection<PSObject> results = s_ps.Invoke();
                Console.WriteLine("Output:");
                foreach (var psObject in results)
                {
                    Console.WriteLine(psObject);
                }
                Console.WriteLine("Non-terminating errors:");
                foreach (ErrorRecord err in s_ps.Streams.Error)
                {
                    Console.WriteLine(err.ToString());
                }
            }
            catch (RuntimeException ex)
            {
                Console.WriteLine("Terminating error:");
                Console.WriteLine(ex.Message);
            }
        }
    }
}

If you run this program it outputs:

Output:
Non-terminating errors:
Cannot find path 'C:\xyzzy' because it does not exist.
Terminating error:
Oops, I did it again.
Press any key to continue . . .
like image 66
Keith Hill Avatar answered Oct 10 '22 22:10

Keith Hill