Raja
Raja

Reputation: 103

How can maintain the powershell remote session throughout the program?

I want to execute some Active directory queries on remote machine using c# language.It is the query

  PowerShell ps = PowerShell.Create();;

 ps.AddScript(@"$Session = New-PSsession -Computername com1");
 ps.AddScript(@"Invoke-Command -Command {Import-Module ActiveDirectory} -Session $Session");
 ps.Invoke();

I want to skip the above command execution after the first execution and should maintain the session until the program exit.Please help me to execute more script with the same session established.

In exact i want to create the session only once in the whole program.Thanks

Upvotes: 0

Views: 1430

Answers (2)

Vic
Vic

Reputation: 2055

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;

Make Powershell object as a static variable in the class.

Upvotes: 0

Raja
Raja

Reputation: 103

Finally i got the solution for my question ..its very simple one.

Make the Powershell object as a static variable and clear the command after script invoke function.

ps.commands.clear();

Now without affecting the current session we can execute the query easily..Let me know if any other efficient way for it.

Thanks.

Upvotes: 1

Related Questions