2013-08-16 121 views
6

我试图运行一个使用C#的invoke-command cmdlet,但我无法弄清楚正确的语法。我只是想运行这个简单的命令:从C#调用远程PowerShell命令#

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类型,但不知道如何去做。这只是一个简单的例子,真正的用例需要运行一个包含多个命令的更大的脚本块,所以如何做到这一点的任何帮助将不胜感激。

感谢

回答

9

啊,参数脚本块本身需要类型的脚本块的。

全码:

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 
} 

把这里的答案,如果有人发现了它在未来

3

一个脚本块串有用的应匹配的格式为“{...}”使用后续代码。会确定:

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

该多好啊,为我节省了作出明确的过滤器对象,谢谢 – NullPointer

0

您可以使用短格式:

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

在某些情况下可能更合适的替代方法。

 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-a-c-love-story/