0

I try to execute a PowerShell script from c# without waiting for the result.

 string cmdArg = "MyScript.ps1";
 //Create New Runspace
 Runspace runspace = RunspaceFactory.CreateRunspace();
 runspace.ApartmentState = System.Threading.ApartmentState.STA;
 runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
 runspace.Open();

 //Adds the command
 pipeline.Commands.AddScript(cmdArg);
 pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

 //Do not wait for a result
 pipeline.InvokeAsync();
 runspace.Close();

But it waits until the script has finished!

2 Answers 2

1

Use BeginInvoke - as highlighted in this msdn sample - http://msdn.microsoft.com/en-us/library/windows/desktop/ee706580(v=vs.85).aspx. The script is run asynchronously and events are used to handle the output.

// Invoke the pipeline asynchronously.
IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);
Sign up to request clarification or add additional context in comments.

Comments

1

Does this help?

http://msdn.microsoft.com/en-us/library/windows/desktop/ms569311(v=vs.85).aspx

The Remarks state that you should use RunSpace.OpenAsync() method for asynch....

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.