Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

.net - Invoke remote powershell command from C#

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"}

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".

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

full 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...