加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Powershell C#异步执行

发布时间:2020-12-15 22:10:09 所属栏目:百科 来源:网络整理
导读:我想在C#中异步执行Power shell脚本.我已经使用了BeginInvoke方法,但即使我为它们附加了委托,我也无法得到输出/错误.这是我的C#代码: using(ps=PowerShell.Create()){ PSDataCollectionPSObject output=new PSDataCollectionPSObject(); output.DataAdded+=
我想在C#中异步执行Power shell脚本.我已经使用了BeginInvoke方法,但即使我为它们附加了委托,我也无法得到输出/错误.这是我的C#代码:

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
}

我的脚本中有多个Write-Output语句.但是,从不触发DataAdded方法.但是当我使用同步Invoke方法时会触发它们.

解决方法

See this answer. 要实际异步运行它,您还需要使方法异步. 您可以通过调用Task.Factory.FromAsync(…)来获取任务< PSObject>对于异步操作,然后使用await.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读