我尝试从c#执行PowerShell脚本而不等待结果。
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();
但它会一直等到脚本完成!
答案 0 :(得分:1)
这有帮助吗?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms569311(v=vs.85).aspx
备注声明你应该使用RunSpace.OpenAsync()方法来实现异步....
答案 1 :(得分:1)
使用BeginInvoke
- 在此msdn示例中突出显示 - http://msdn.microsoft.com/en-us/library/windows/desktop/ee706580(v=vs.85).aspx。该脚本运行asynchronously
和events are used to handle the output
。
// Invoke the pipeline asynchronously.
IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);