Question:
I am writing a program that will run a program on a remote machine.
I have installed the windows sdk and have successfully uploaded my file with bits
now I would like to remotely run a change directory and execute a command using
power shell.
The program compiles and runs but in the answer variable it says: “The method or operation is not implemented.\r\n”
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 |
// create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); // open it runspace.Open(); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript("Enter-PSSession " + host + Environment.NewLine + "cd " + uploadtodir + Environment.NewLine + command + Environment.NewLine + "exit" + Environment.NewLine + "exit" + Environment.NewLine); // add an extra command to transform the script output objects into nicely formatted strings // remove this line to get the actual objects that the script returns. For example, the script // "Get-Process" returns a collection of System.Diagnostics.Process instances. pipeline.Commands.Add("Out-String"); // execute the script Collection try { results = pipeline.Invoke(); } catch (Exception ex) { results.Add(new PSObject((object)ex.Message)); } // close the runspace runspace.Close(); // convert the script result into a single string StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } string answer = stringBuilder.ToString(); |
I tried to use another command in the pipeline but it fails also but with no error output.
1 2 |
**pipeline.Commands.AddScript("$sessions = New-PSSession -ComputerName " + host + Environment.NewLine + "Invoke-Command -session $sessions -ScriptBlock {cd " + uploadtodir+"}" + Environment.NewLine+"Invoke-Command -session $sessions -ScriptBlock {"+command+ "}" + Environment.NewLine + "Remove-PSSession -Session $sessions" + Environment.NewLine + "exit" + Environment.NewLine + "exit" + Environment.NewLine);** |
Answer:
This line fixed it.
1 2 3 4 5 6 |
pipeline.Commands.AddScript("$sessions = New-PSSession -ComputerName " + host + Environment.NewLine + "Invoke-Command -session $sessions -ScriptBlock {cd " + uploadtodir+"}" + Environment.NewLine +"Invoke-Command -session $sessions -ScriptBlock {"+command+ "}" + Environment.NewLine + "Remove-PSSession -Session $sessions" + Environment.NewLine + "exit" + Environment.NewLine + "exit" + Environment.NewLine); |