0

我尝试从 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();

但它要等到脚本完成!

4

2 回答 2

1

这有帮助吗?

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

备注说明您应该使用 RunSpace.OpenAsync() 方法进行异步......

于 2012-07-04T11:00:24.657 回答
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);
于 2012-07-04T20:54:47.190 回答