使用C#在远程计算机上执行Powershell脚本
问题描述:
我已经使用Microsoft Bot Framework创建了Bot应用程序,并希望实现以下目标:
I have created a Bot Application using Microsoft Bot Framework and want to achieve the following:
- 无需任何身份验证即可在远程计算机上执行Powershell脚本
- powershell脚本将托管在Azure或数据库(可能是任何主机)上
到目前为止,我已经完成以下操作:
I have done following till now:
- 能够在远程计算机上手动执行Powershell脚本
- 能够使用C#代码在本地执行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();
}
答
我认为您缺少PowerShell
实例与运行空间的绑定.
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();