从C#调用远程PowerShell命令

11

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

谢谢

4个回答

16

啊,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
}

如果有人在将来发现这个答案有用,就把答案放在这里。


3
一个脚本块字符串应该匹配格式为"{ ... }"。使用以下代码将是正确的:

一个脚本块字符串应该匹配格式为"{ ... }"。使用以下代码将是正确的:

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

啊,太好了,这让我不用创建一个显式的过滤器对象了,谢谢。 - NullPointer

2
在某些情况下,可能会采用另一种方法,这可能更加合适。
        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/


2
您使用的是短格式:
ps.AddParameter("ScriptBlock", ScriptBlock.Create("Get-childitem C:\\Windows"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接