从C#调用远程powershell命令

本文关键字:powershell 命令 调用 | 更新日期: 2023-09-27 18:27:55

我正试图使用C#运行invoke命令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类型,但不知道如何使用。这只是一个简单的入门示例,真正的用例将涉及运行一个更大的脚本块,其中包含多个命令,因此非常感谢有关如何做到这一点的任何帮助。

感谢

从C#调用远程powershell命令

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

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