1

I have created a Bot Application using Microsoft Bot Framework and want to achieve the following:

  1. To execute a Powershell script on remote computers without any authentication
  2. The powershell scripts will be hosted on Azure or on a Database (may be any)

I have done following till now:

  1. Was able to execute Powershell scripts on remote computers manually
  2. Was able to execute Powershell scripts locally using C# code

Below is my current code:

WSManConnectionInfo connectioninfo = new WSManConnectionInfo();
connectioninfo.ComputerName = "<remote computer hostname>";
Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo); 
//runspace.Open();
using (PowerShell ps = PowerShell.Create())
{ 
   var re = ps.AddScript("Get-Service"); 
   var results = re.Invoke(); 
}
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
zee
  • 51
  • 1
  • 7
  • 3
    Who are the owners of the remote computers? Are they fully within your control - Do you manage the security policies for them? – Dylan Morley Jun 13 '17 at 11:21
  • 2
    You can use [Invoke-Command](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/invoke-command) if the remote computer has [PSRemoting](https://msdn.microsoft.com/powershell/reference/5.1/microsoft.powershell.core/Enable-PSRemoting) enabled. – henrycarteruk Jun 13 '17 at 11:30
  • 1
    Hi Dylan/ James, I am not the owner of remote computers. I will be creating an administrator with which the Bot can login into remote computers and do the administrative stuff. Invoke-Command works fine from the powershell windows and with the manual intervention. I am searching a way to do the automatic remoting stuff through C# code. – zee Jun 13 '17 at 12:30
  • @zee do you happened to solve the issue now? I have exactly same situation with you. really need help on this... – HNA Feb 26 '19 at 07:49

1 Answers1

2

I think that you are missing the bind of your PowerShell instance to the runspace.

ps.Runspace = runspace;

Take a look to this for more details.

Alternatively, you can create a Pipeline (as explained here) using the runspace and invoke the commands.

Pipeline pipeline = runspace.CreatePipeline("<COMMAND TO EXECUTE REMOTELY>");

var results = pipeline.Invoke();
Ezequiel Jadib
  • 14,767
  • 2
  • 38
  • 43