Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在整个程序中维护powershell远程会话?_C#_Active Directory_Powershell Remoting_Import Module - Fatal编程技术网

C# 如何在整个程序中维护powershell远程会话?

C# 如何在整个程序中维护powershell远程会话?,c#,active-directory,powershell-remoting,import-module,C#,Active Directory,Powershell Remoting,Import Module,我想使用c语言在远程计算机上执行一些Active directory查询。这就是查询 PowerShell ps = PowerShell.Create();; ps.AddScript(@"$Session = New-PSsession -Computername com1"); ps.AddScript(@"Invoke-Command -Command {Import-Module ActiveDirectory} -Session $Session"); ps.Invoke

我想使用c语言在远程计算机上执行一些Active directory查询。这就是查询

  PowerShell ps = PowerShell.Create();;

 ps.AddScript(@"$Session = New-PSsession -Computername com1");
 ps.AddScript(@"Invoke-Command -Command {Import-Module ActiveDirectory} -Session $Session");
 ps.Invoke();
我想在第一次执行后跳过上面的命令执行,并且应该在程序退出之前保持会话。请帮助我在建立相同会话的情况下执行更多脚本


确切地说,我只想在整个程序中创建一次会话。谢谢

最后我得到了我问题的解决方案。它非常简单

将Powershell对象设为静态变量,并在脚本调用函数后清除该命令

ps.commands.clear();
现在,在不影响当前会话的情况下,我们可以轻松执行查询。如果有其他有效的方法,请告诉我

谢谢

int iRemotePort = 5985;
string strShellURI = @"http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
string strAppName = @"/wsman";
AuthenticationMechanism auth = AuthenticationMechanism.Negotiate;

WSManConnectionInfo ci = new WSManConnectionInfo(
    false,
    sRemote,
    iRemotePort,
    strAppName,
    strShellURI,
    creds);
ci.AuthenticationMechanism = auth;

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

PowerShell psh = PowerShell.Create();
psh.Runspace = runspace;
将Powershell对象设为类中的静态变量