繁体   English   中英

在C#WPF中保持Powershell运行空间正常运行?

[英]Keeping a powershell runspace alive in C# WPF?

我正计划使用C# powershellDC和Exchange服务器进行通讯来构建Active Directory/Exchange管理控制台。

我想在应用程序启动时建立与这些服务器的powershell连接,然后使其保持活动状态,这样我就可以继续运行查询或脚本或其他任何东西,因为建立远程连接需要花费几秒钟的时间,而建立这种连接是行不通的延迟您所做的一切。

我目前只是测试本地powershell运行空间,但每一次我将命令发送给它的时候它会关闭,初始命令后,我无法重复使用。

如何防止运行runspace关闭,以便可以一遍又一遍地使用它?

编辑:代码非常基本,只是创建一个运行空间,计划在以后我不再使用基本功能时就可以包含模块。 想法是创建一个运行空间,并在调用执行powershell代码的函数时将该运行空间分配给另一个变量,这样我就可以重用它,但是我可能很愚蠢。 当前,我只有一个虚拟的“ Get-Process”,它在单击按钮和显示输出的文本框时发送。

public partial class MainWindow : Window
{
    Runspace powerShellRunspace = RunspaceFactory.CreateRunspace();
    public MainWindow()
    {

        InitializeComponent();
        powerShellRunspace.Open();
        string[] modules;
        scriptOutput.Text = "test";
        modules = new string[5];
        modules[0] = "john";



        //string result = powerShellRun("Get-Process");
        //powerShellInitialize(modules);

    }

    public static void powerShellInitialize(string[] modules)
    {
        Runspace powerShellRunspace = RunspaceFactory.CreateRunspace();
        powerShellRunspace.Open();

    }

    public string powerShellRun(string commands, Runspace powerShellRunspace)
    {

        Runspace powerShellRunspace2 = powerShellRunspace;
        Pipeline powerShellPipeline = powerShellRunspace2.CreatePipeline();
        powerShellPipeline.Commands.Add(commands);
        Collection<PSObject> powerShellResult = powerShellPipeline.Invoke();
        //string result="temp";
        //return result;
        StringBuilder stringBuilder = new StringBuilder();
        foreach (PSObject obj in powerShellResult)
        {
            stringBuilder.AppendLine(obj.ToString());
        }

        return stringBuilder.ToString();

    }
}

关于在.Net中保持Powershell运行空间打开的问题,已经回答了。

总而言之,您可以使Runspace保持打开状态,但是对于每个独立的查询,您都需要创建一个新的Powershell实例。

例:

Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();

//First Query
var firstQuery = PowerShell.Create();
firstQuery.Runspace = runspace;
firstQuery.AddScript("Write-Host 'hello'")

//Second Query
var secondQuery = PowerShell.Create();
secondQuery.Runspace = runspace;
secondQuery.AddScript("Write-Host 'world'")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM