Execute powershell script on a remote computer using C#

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

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();  } 

回答1:

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(); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!