使用C#在远程计算机上执行powershell脚本

时间:2017-06-13 10:59:22

标签: c# powershell botframework

我使用Microsoft Bot Framework创建了一个Bot应用程序,并希望实现以下目标:

  1. 在没有任何身份验证的情况下在远程计算机上执行Powershell脚本
  2. powershell脚本将托管在Azure或数据库(可能是任何)
  3. 到目前为止,我一直关注着:

    1. 能够手动在远程计算机上执行Powershell脚本
    2. 能够使用C#代码
    3. 在本地执行Powershell脚本

      以下是我目前的代码:

      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 个答案:

答案 0 :(得分:1)

我认为您错过了ps.Runspace = runspace; 实例与运行空间的绑定。

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

var results = pipeline.Invoke();

请查看this了解详情。

或者,您可以使用运行空间创建管道(如here所述)并调用命令。

@DeleteMapping("/")
public MyObject delete(@RequestParam("id")MyObject object){
...do something
}