C# 从C调用远程powershell命令#

C# 从C调用远程powershell命令#,c#,.net,powershell,C#,.net,Powershell,我正在尝试使用C#运行invoke-command cmdlet,但找不出正确的语法。我只想运行这个简单的命令: invoke-command -ComputerName mycomp.mylab.com -ScriptBlock {"get-childitem C:\windows"} 在C#代码中,我做了以下工作: InitialSessionState initial = InitialSessionState.CreateDefault(); Runspace runspace = R

我正在尝试使用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
}

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

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

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();

啊,很好,省去了我制作显式过滤对象的麻烦,谢谢