0

I have a powershell script which is run by c#. Below is my code:

string data = System.IO.File.ReadAllText(@"C:\Users\user1\Desktop\power.ps1");
using (PowerShell PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript(data);
    IAsyncResult result = PowerShellInstance.BeginInvoke();
    while (!result.IsCompleted)
    {
        Logger.Info("Wait initiated");
        Thread.Sleep(5000);
    }
}

How can I read the exit code after completing the script?

Palle Due
  • 5,929
  • 4
  • 17
  • 32
Ijas
  • 367
  • 1
  • 3
  • 18

1 Answers1

1

From here Executing PowerShell scripts from C#

// begin invoke execution on the pipeline
// use this overload to specify an output stream buffer
IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);

...

foreach (PSObject outputItem in outputCollection)
{
    //TODO: handle/process the output items if required
    Console.WriteLine(outputItem.BaseObject.ToString());
}
user2316116
  • 6,726
  • 1
  • 21
  • 35