user2242800
user2242800

Reputation: 41

Remote execution of Powershell Version 2 using C#

I am writing a C# application that triggers execution of a powershell script on a remote server.

The machine where the execution is called from (local dev box) has Powershell Version 2, Version 3, And Version 4 installed as per displayed by $PSVersionTable.PSVersion, on the server, the result is the same.

I ran my code on a test server and it works fine when using V4.0

The issue im having is that on the actual server the commands need to run as a powershell V2.0 and not a V4.0.

I created a New-PSSessionConfigurationFile and then i used Registe-rPSSessionConfiguration to resister the version 2.0 configuration, then i ran Enable-PSRemoting and i set to enable it, and i selected No to all configurations that are NOT v2.0.

But now when i run the scripts from my dev box, they still report a powershell version 4.0

does anyone know how to force remote powershell execution using version 2.0 and using C#

this is my Code

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); 
connectionInfo.ComputerName = computerIdent.ToLowerInvariant();

Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();

StreamReader sReader = new StreamReader("C:\Script\Mysqcript.ps1");
PowerShell psExec = PowerShell.Create();
psExec.Runspace = runspace;
psExec.AddScript(sReader.ReadToEnd()); //reads all the lines in the powershell script

powershellResults = psExec.Invoke();

Upvotes: 2

Views: 1075

Answers (1)

user2242800
user2242800

Reputation: 41

What I ended up doing is on the remote machine I changed the version that the Session Configuration microsoft.powershell is using so I ran this command to change that:

Set-PSSessionConfiguration -name microsoft.powershell -psversion 2.0 -FORCE

Upvotes: 1

Related Questions