我正在尝试使用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类型,但不知道如何做。这只是一个简单的示例,以便开始学习,真正的用例将涉及运行包含多个命令的较大脚本块,因此对于如何执行此操作的任何帮助都将非常感激。
谢谢