在C#中异步运行Powershell脚本

时间:2019-03-22 07:41:14

标签: c# winforms powershell asynchronous

我正在尝试对现有的C#Winforms工具进行返工。 想法是将Powershell用于对计算机的特定命令。

我有一个BindingList,在单击按钮时将用ADComputer对象填充它们,这些计算机将被异步ping通。当每台机器返回其ping时,该代码先前都会使用ManagementOperationObserver触发WMI查询。在ObjectReady上,它将返回登录的用户名。

出于性能和维护的原因,我想将Powershell用于代码的WMI部分。

我当时在考虑Powershell自动化类,但是当脚本完成后需要向GUI报告时,我需要一个事件。由于这将是异步操作,因此代码也不应阻止其他计算机执行代码。我不知道这是否是最好的选择。

这是代码设置:

private BindingList<ADComputer> ADComputers = new BindingList<ADComputer>();

private void SearchADButton_Click(object sender, EventArgs e) {
            ADComputers.Clear();

            //Code to fill ADComputers...

            for (int i = 0; i < ADComputers.Count; i++) {
                int index = i;
                Ping ping = new Ping();
                ping.PingCompleted += (sender2, e2) => Ping_PingCompleted(sender2, e2, index);
                ping.SendPingAsync(ADComputers[i].Name);
            }
        }

private void Ping_PingCompleted(object sender, PingCompletedEventArgs e, int index) {
            if(e.Error == null && e.Reply.Status.Equals(IPStatus.Success)) {
                ADComputers[index].Online = "Online";
                PClist.InvalidateRow(index);

                //Powershell goes here!!!
            }
            else {
                ADComputers[index].Online = "Offline";
                ADComputers[index].LoggedIn = "/";
                PClist.InvalidateRow(index);
            }
        }

任何人都可以解释和/或举例说明这样做的最佳做法吗?

0 个答案:

没有答案
相关问题