Powershell C#异步执行

Powershell C#异步执行,c#,powershell,asynchronous,C#,Powershell,Asynchronous,我想在C#中异步执行Powershell脚本。我使用了BeginInvoke方法,但是我无法获得输出/错误,即使我已经为它们附加了代理。这是我的C#代码: 使用(ps=PowerShell.Create()) { PSDataCollection输出=新的PSDataCollection(); output.DataAdded+=output\u DataAdded; ps.AddScript(续订脚本); SecureString ss=新的SecureString(); for(int i=

我想在C#中异步执行Powershell脚本。我使用了
BeginInvoke
方法,但是我无法获得输出/错误,即使我已经为它们附加了代理。这是我的C#代码:

使用(ps=PowerShell.Create())
{
PSDataCollection输出=新的PSDataCollection();
output.DataAdded+=output\u DataAdded;
ps.AddScript(续订脚本);
SecureString ss=新的SecureString();
for(int i=0;i
我的脚本中有多个
Write Output
语句。但是,
DataAdded
方法从不触发。但是当我使用synchronous
Invoke
方法时,它们会被触发。

。 要实际异步运行它,还需要使方法异步。
您可以通过调用
Task.Factory.fromsync(…)
获取异步操作的
Task
,然后使用
wait

获得一个带有异步
BeginInvoke
的using语句。主机
PowerShell
对象将在命令管道完成之前被释放。
using(ps=PowerShell.Create())
{
    PSDataCollection<PSObject> output=new PSDataCollection<PSObject>();
    output.DataAdded+=output_DataAdded;
    ps.AddScript(RenewalScript);
    SecureString ss = new SecureString();
    for (int i = 0; i < Password.Length; i++)
        ss.AppendChar(Password.ElementAt(i));

    PSCredential cred = new PSCredential(Username, ss);
    ps.AddParameter("Credential", cred);
    ps.AddParameter("BuildServer", Server);
    ps.AddParameter("CAServer", CAServer);
    ps.AddParameter("CAName", CAName);
    ps.Streams.Error.DataAdded += Error_DataAdded;
    var result=ps.BeginInvoke<PSObject, PSObject>(null, output);

}

void output_DataAdded(object sender, DataAddedEventArgs e)
{
    //display output in UI
}

void Error_DataAdded(object sender, DataAddedEventArgs e)
{
    //display error message in UI
}