c# - 从 C# 调用远程 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 = 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/

相关文章:

c# - WP8 - 将命令绑定(bind)到列表中的按钮和开关

.net - 添加新的 NuGet 包时如何解决 OutOfMemoryException 错误?

.net - 析构函数和垃圾收集器的区别

linux - Linux和Windows之间的文本编码

powershell - PowerShell 模块中的内部函数

c# - 字典的 IEnumerator 是否保证一致?

c# - 如何从特定程序集引用命名空间?

c# - LINQ 查询 if 条件外部参数

c# - 并发访问 .NET 中的静态成员

c# - 使用 System.Management.Automation 调用 powershell 时如何从远程命令传递警告和详细流?