Execute Powershell Script in Remote Machine using C#

Sai Komal Pendela
Quick Code
Published in
May 9, 2021
Photo by Bram Van Oost on Unsplash

You can run the PowerShell script in the remote machine by using the Invoke-Command argument while running the script in the interpreter. But in order to achieve similar functionality in C#, we use something called RunSpace from System.Management.Automation.dll.

First, we need to create WSManConnectionInfo object using the credentials to connect to the remote machine. The connectionInfo object we just created should be sent as a parameter while creating the runspace. By runspace.Open() a new connection is created to the remote machine.

In the above gist, the script being run is actually present in the machine where the c# code is being executed. In order to run the ps script on the remote machine, we can use

ps.AddScript(scriptLocation);

We can pass arguments to the script using

ps.AddArgument(@"Argument1");

In order to run the script a reference to System.Management.Automation must be added.

--

--

Sai Komal Pendela
Quick Code

Full Stack Developer | Sharing my opinion on what I learn