Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 250
NullPointer Avatar asked Aug 16 '13 15:08

NullPointer


People also ask

How do I trigger a PowerShell script remotely?

To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command cmdlet. The script must be on or accessible to your local computer. The results are returned to your local computer.

How do you execute a PowerShell command?

To run a command in a background job, use the AsJob parameter. You can also use Invoke-Command on a local computer to a run script block as a command. PowerShell runs the script block immediately in a child scope of the current scope. Before using Invoke-Command to run commands on a remote computer, read about_Remote.

Which commands allow you to send a PowerShell command to a remote host?

Use the Enable-PSRemoting cmdlet to enable PowerShell remoting. WinRM has been updated to receive requests.


1 Answers

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

like image 96
NullPointer Avatar answered Oct 02 '22 14:10

NullPointer