Running Powershell Command Remotely Using C#

C# has some really awesome nuget package if you want to run the PowerShell script or run the command. I am talking about the nuget package "Microsoft.PowerShell.SDK".

Now running the batch file or any command or any executable from the local machine is quite easy and simple. You just need to create the PowerShell object, add the script you want to execute and invoke it.


Above code is simple and self explanatory. But lately in my project we had a requirement in which we need to execute the command on the remote machine and fetch the output. It's as good as you are remoting to that machine and executing the command on that machine and fetching the output.

Now you would be surprised to know that, you can actually achieve that using the PowerShell SDK and with only few lines of code you can create the magic.

PowerShell SDK provides something called as "RunSpace". When you create the RunSpace object you need to provide the machine details and corresponding credentials if any and it will create the RunSpace object which you can later feed to the PowerShell object and after that whatever command you run will directly on the Remote Machine.

Below is the code which I wrote:


Firstly we need the "WSManConnectionInfo" object, to which we provide all the remote machine details. Later you can either create the Runspace object or RunspacePool object.

If you have a multi-threading application make sure to use the RunSpacePool object because if you have only only one RunSpace object than the Thread will wait till the previous thread is done using the RunSpace. And since mine was multi-threading I used RunspacePool and thread can consume whichever Runspace pool is free.

Anyways, once you are done creating the Runspace object, you can feed that to the PowerShell object.

And that's it, now all the commands will be executed on the remote machine. Good thing is, you can deploy on any machine you want unless you have the remote access to that machine.

With less than 20 lines of code you can actually connect to the remote machine and execute all the commands. So now you can have one Production Setup machine and you can deploy the application across different machine and can directly connect to the Prod machine and run the commands.

I hope it was useful. Happy Coding.

Rishi


Comments

Popular posts from this blog

Deploying Asp.net Core Background Service on IIS

Map IIS Worker Process to PID