Guest User

Untitled

a guest
Jul 2nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. public class GetPSConnection
  2. {
  3.  
  4.  
  5. public void ExecutePS()
  6. {
  7. string server = "*******";
  8. string password = "********";
  9. string userName = "*******";
  10.  
  11. System.Security.SecureString securePassword = String2SecureString(password);
  12. PSCredential creds = new PSCredential(userName, securePassword);
  13.  
  14.  
  15. Runspace runspace = RunspaceFactory.CreateRunspace();
  16.  
  17. PowerShell ps = PowerShell.Create();
  18. PSCommand command = new PSCommand();
  19. command.AddCommand("$Session = New-PSSession");
  20. command.AddParameter("ComputerName", server);
  21. command.AddParameter("Credential", creds);
  22. command.AddParameter("Name", server);
  23. command.AddParameter("UseSSL", true);
  24.  
  25. ps.Commands = command;
  26. //calling the command
  27. try
  28. {
  29. runspace.Open();
  30. ps.Runspace = runspace;
  31. Collection<PSSession> result = ps.Invoke<PSSession>();
  32.  
  33. //logging any errors
  34. foreach (ErrorRecord current in ps.Streams.Error)
  35. {
  36. Console.WriteLine("Exception: " + current.Exception.ToString());
  37. Console.WriteLine("Inner Exception: " + current.Exception.InnerException);
  38. }
  39.  
  40. foreach (PSSession r in result)
  41. {
  42. //this is just for test
  43. Console.WriteLine(r);
  44.  
  45. }
  46.  
  47. }
  48. //clearing the runspace
  49. finally {
  50. runspace.Dispose();
  51. runspace = null;
  52.  
  53. }
  54.  
  55. }
  56. //creating and formating the credentials
  57. private static SecureString String2SecureString(string password)
  58. {
  59. SecureString remotePassword = new SecureString();
  60. for (int i = 0; i < password.Length; i++)
  61. remotePassword.AppendChar(password[i]);
  62.  
  63. return remotePassword;
  64. }
  65. }
  66.  
  67. public class Program
  68. {
  69. static void Main(string[] args)
  70. {
  71. GetPSConnection Getpscon = new GetPSConnection();
  72. Getpscon.ExecutePS();
  73. }
  74.  
  75. }
  76. }
Add Comment
Please, Sign In to add comment