我正在尝试使用 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 类型,但不知道如何使用。这只是一个简单的入门示例,真正的用例将涉及运行一个更大的脚本 block ,其中包含多个命令,因此非常感谢任何有关如何执行此操作的帮助。
谢谢
最佳答案
啊,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
}
如果以后有人觉得有用就把答案放在这里
关于c# - 从 C# 调用远程 powershell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18277308/