PowerShell的C#异步执行 [英] Powershell C# asynchronous execution

查看:582
本文介绍了PowerShell的C#异步执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C#中异步执行PowerShell脚本。我使用的BeginInvoke 方法,但我不能让即使我已经附加了他们代表输出/错误。这里是我的C#code:

I want to execute a Powershell script asynchronously in C#. I've used BeginInvoke method but I can't get the output/errors even though I've attached delegates for them. Here is my C# code:

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
}

我在我的脚本多个写输出语句。然而,永远不会触发 DataAdded 方法。但是,当我使用同步调用方法就可以触发。

I have multiple Write-Output statements in my script. However, the DataAdded methods are never triggered. But they are triggered when I use the synchronous Invoke method.

推荐答案

看到这个答案
要真正运行它以异步方式,你需要让你的方法也同步。
你可以通过调用 Task.Factory.FromAsync(...)获得任务&LT; PSObject&GT; 的异步操作,然后使用等待

See this answer. To actually run it asynchronously, you need to make your method asynchronous too. You can do that by calling Task.Factory.FromAsync(...) to get a Task<PSObject> for the asynchronous operation, then using await.

这篇关于PowerShell的C#异步执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆