2

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

我想在应用程序启动时建立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();

    }
}
4

1 回答 1

1

这个问题已经在Keeping Powershell runspace open in .Net上得到解答

总之,您可以保持运行空间打开,但是对于每个独立的查询,您需要创建一个新的 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'")
于 2017-04-12T20:03:21.077 回答