Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class GetPSConnection
- {
- public void ExecutePS()
- {
- string server = "*******";
- string password = "********";
- string userName = "*******";
- System.Security.SecureString securePassword = String2SecureString(password);
- PSCredential creds = new PSCredential(userName, securePassword);
- Runspace runspace = RunspaceFactory.CreateRunspace();
- PowerShell ps = PowerShell.Create();
- PSCommand command = new PSCommand();
- command.AddCommand("$Session = New-PSSession");
- command.AddParameter("ComputerName", server);
- command.AddParameter("Credential", creds);
- command.AddParameter("Name", server);
- command.AddParameter("UseSSL", true);
- ps.Commands = command;
- //calling the command
- try
- {
- runspace.Open();
- ps.Runspace = runspace;
- Collection<PSSession> result = ps.Invoke<PSSession>();
- //logging any errors
- foreach (ErrorRecord current in ps.Streams.Error)
- {
- Console.WriteLine("Exception: " + current.Exception.ToString());
- Console.WriteLine("Inner Exception: " + current.Exception.InnerException);
- }
- foreach (PSSession r in result)
- {
- //this is just for test
- Console.WriteLine(r);
- }
- }
- //clearing the runspace
- finally {
- runspace.Dispose();
- runspace = null;
- }
- }
- //creating and formating the credentials
- private static SecureString String2SecureString(string password)
- {
- SecureString remotePassword = new SecureString();
- for (int i = 0; i < password.Length; i++)
- remotePassword.AppendChar(password[i]);
- return remotePassword;
- }
- }
- public class Program
- {
- static void Main(string[] args)
- {
- GetPSConnection Getpscon = new GetPSConnection();
- Getpscon.ExecutePS();
- }
- }
- }
Add Comment
Please, Sign In to add comment