从C#调用远程PowerShell命令 [英] Invoke remote powershell command from C#

查看:2018
本文介绍了从C#调用远程PowerShell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C#来运行一个调用命令cmdlet的,但我不能找出正确的语法。我只是想运行这个简单的命令:

I'm trying to run an invoke-command cmdlet using C# but I can't figure out the right syntax. I just want to run this simple command:

invoke-command -ComputerName mycomp.mylab.com -ScriptBlock {"get-childitem C:\windows"}

在C#code,我也做了以下内容:

In C# code, I have done the following:

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
}

当我运行它,我得到一个异常:

When I run this, I get an exception:

Cannot bind parameter 'ScriptBlock'. Cannot convert the "get-childitem C:\windows" value of type "System.String" to type "System.Management.Automation.ScriptBlock".

我猜我需要使用脚本块型这里的某个地方,但不知道怎么样。这只是一个简单的例子来上手,真正的用例将涉及运行在它的多个命令,一个更大的脚本块,所以对如何做到这一点任何帮助将是非常美联社preciated。

I'm guessing I need to use ScriptBlock type here somewhere, but don't know how to. This is just a simple example to get started with, the real use case would involve running a larger script block with multiple commands in it, so any help on how to do this would be highly appreciated.

感谢

推荐答案

嗯,脚本块本身的参数需要类型的脚本块的。

Ah, the parameter to ScriptBlock itself needs to be of type ScriptBlock.

满code:

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
}

把答案在这里如果有人发现它的未来有用

Putting the answer here if someone finds it useful in the future

这篇关于从C#调用远程PowerShell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆