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?

1
  • I don't see any exit code in your code. There is not even an "exit"... Commented Aug 31, 2023 at 9:36

1 Answer 1

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

what is outputCollection?
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
That doesn't really answer the question but maybe the question itself is wrong. The exit code is stored in $LASTEXITCODE but this doesn't seem to be too easy to use in C#: stackoverflow.com/a/780047/2523899

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.