我正计划使用与 Exchange 服务器进行对话来构建Active Directory/Exchange
管理控制台。C#
powershell
DC
我想在应用程序启动时建立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();
}
}