Call remote powershell command from C #

I am trying to run the invoke-command cmdlet using C #, but I cannot figure out the correct syntax. I just want to run this simple command:

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

In C # code, I did 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 assume that I need to use the ScriptBlock type here, but don't know how to do it. This is a simple example to get started, in the real case of use, a larger script block will be involved with several commands in it, so any help on how to do this will be highly appreciated.

thanks

+6
source share
4 answers

Ah, the ScriptBlock parameter itself must 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 } 

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

+9
source

The scriptblock line must match the format as "{...}". Using the following code will be fine:

 ps.AddParameter("ScriptBlock", "{ get-childitem C:\\windows }"); 
+3
source

You are using a short format:

 ps.AddParameter("ScriptBlock", ScriptBlock.Create("Get-childitem C:\\Windows")); 
0
source

An alternative approach if it may be more appropriate in some cases.

  var remoteComputer = new Uri(String.Format("{0}://{1}:5985/wsman", "HTTP", "ComputerName")); var connection = new WSManConnectionInfo(remoteComputer, null, TopTest.GetCredential()); var runspace = RunspaceFactory.CreateRunspace(connection); runspace.Open(); var powershell = PowerShell.Create(); powershell.Runspace = runspace; powershell.AddScript("$env:ComputerName"); var result = powershell.Invoke(); 

https://blogs.msdn.microsoft.com/schlepticons/2012/03/23/powershell-automation-and-remoting-ac-love-story/

0
source

Source: https://habr.com/ru/post/951899/


All Articles