从C#调用远程PowerShell命令命令、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...

我想用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

阅读全文

相关推荐

最新文章