从C#调用远程powershell命令

我正在尝试使用C#运行invoke-command cmdlet,但我无法找出正确的语法。 我只想运行这个简单的命令:

invoke-command -ComputerName mycomp.mylab.com -ScriptBlock {"get-childitem C:\windows"} 

在C#代码中,我做了以下事情:

 InitialSessionState initial = InitialSessionState.CreateDefault(); Runspace runspace = RunspaceFactory.CreateRunspace(initial); runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.AddCommand("invoke-command"); ps.AddParameter("ComputerName", "mycomp.mylab.com"); ps.AddParameter("ScriptBlock", "get-childitem C:\\windows"); foreach (PSObject obj in ps.Invoke()) { // Do Something } 

当我运行它时,我得到一个例外:

 Cannot bind parameter 'ScriptBlock'. Cannot convert the "get-childitem C:\windows" value of type "System.String" to type "System.Management.Automation.ScriptBlock". 

我猜我需要在某处使用ScriptBlock类型,但不知道该怎么做。 这只是一个简单的示例,真正的用例将涉及运行一个包含多个命令的更大的脚本块,因此任何有关如何执行此操作的帮助都将受到高度赞赏。

谢谢

啊,ScriptBlock本身的参数需要是ScriptBlock类型。

完整代码:

 InitialSessionState initial = InitialSessionState.CreateDefault(); Runspace runspace = RunspaceFactory.CreateRunspace(initial); runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.AddCommand("invoke-command"); ps.AddParameter("ComputerName", "mycomp.mylab.com"); ScriptBlock filter = ScriptBlock.Create("Get-childitem C:\\windows"); ps.AddParameter("ScriptBlock", filter); foreach (PSObject obj in ps.Invoke()) { // Do Something } 

如果有人认为将来有用,请在此处给出答案

scriptblock字符串应与“{…}”格式匹配。使用以下代码即可:

 ps.AddParameter("ScriptBlock", "{ get-childitem C:\\windows }"); 

你使用短格式:

 ps.AddParameter("ScriptBlock", ScriptBlock.Create("Get-childitem C:\\Windows")); 

如果在某些情况下可能更合适,可采用另一种方法。

  var remoteComputer = new Uri(String.Format("{0}://{1}:5985/wsman", "HTTP", "ComputerName")); var connection = new WSManConnectionInfo(remoteComputer, null, TopTest.GetCredential()); var runspace = RunspaceFactory.CreateRunspace(connection); runspace.Open(); var powershell = PowerShell.Create(); powershell.Runspace = runspace; powershell.AddScript("$env:ComputerName"); var result = powershell.Invoke(); 

https://blogs.msdn.microsoft.com/schlepticons/2012/03/23/powershell-automation-and-remoting-ac-love-story/