Code snippet for running power shell on a remote machine. Loosely based on blog post here and here

Add reference to System.Management.Automation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Management.Automation;
using System.Management.Automation.Runspaces;


  internal void runPowershellRemotely(string location, string scriptToBeRun)
        {
            string userName = ConfigurationManager.AppSettings["RemoteMachineLogonUser"];
            string password = ConfigurationManager.AppSettings["RemoteMachineUserPassword"];
           var securestring = new SecureString();
            foreach (Char c in password){
                securestring.AppendChar(c);
            }

            PSCredential creds = new PSCredential(userName, securestring);
            // Remove logging if not needed
            log.Info(String.Format("\tPOWERSHEL : Running Powershell {0} at location {1}", scriptToBeRun, location));
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo();

           connectionInfo.ComputerName = ConfigurationManager.AppSettings["RemoteMachine"];
            connectionInfo.Credential = creds;
            Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
            runspace.Open();
            using (PowerShell ps = PowerShell.Create())
            {
                ps.Runspace = runspace;
                ps.AddScript(@"cd "+ location);
                ps.AddScript(scriptToBeRun);
                try
                {
                    var results = ps.Invoke();
                    log.Info("\tPOWERSHEL : Results from Powershell Script is ---------------------------");
                    foreach(var x in results)
                    {
                        log.Info(x.ToString());
                    }
                    log.Info("\tPOWERSHEL : End of results--------------------------------- ---------------------------");
                }
                catch (Exception e)
                {
                    log.Error("\tPOWERSHEL : Exception from running Powershell Script is" + e.ToString());
                }

            }
            runspace.Close();
        }

Comments