Ahmad
Ahmad

Reputation: 13426

How do I get environment variable value from remote powershell C# code?

I'm connecting to a remote machine through C# Powershell libraries and want to get environment variables from that machine through C# code. From searching on other stack overflow threads, I thought that something like the following would work:

using (var psShell = PowerShell.Create())
{
    using (var remoteRunspace = RunspaceFactory.CreateRunspace(CreateSession()))
    {
        remoteRunspace.Open();
        psShell.Runspace = remoteRunspace;

        string userProfilePath = remoteRunspace.SessionStateProxy.PSVariable.GetValue("env:USERPROFILE").ToString();
    }
}

However it doesn't work. I get a Specified method is not supported exception ... Drilling further, I see that SessionStateProxy has properties which aren't initiated because of a PSNotSupportedException:

enter image description here

Looking at powershell code, this makes sense too: https://github.com/PowerShell/PowerShell/blob/b1e998046e12ebe5da9dee479f20d479aa2256d7/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs#L3310

So how do I get an environment variable value via C# remote powershell code, WITHOUT simply running a remote script to output the value or something (which I don't want to do as it's not the proper way) ?

Upvotes: 0

Views: 1612

Answers (1)

picolino
picolino

Reputation: 5459

If you need a full list of environment variables on target machine or just one of it use following code:

using (var psShell = PowerShell.Create())
{
    // Set up remote connection code

    // Empty means that you will get all environment variables on target machine. 
    // You can use specific environment variable name to get only one.
    var environmentVariableName = string.Empty; 

    psShell.AddCommand("Get-ChildItem")
           .AddParameter("Path", $"Env:\\{environmentVariableName}");

    var environmentVariablesDictionary = psShell.Invoke<DictionaryEntry>(); // Here will be dictionary of environment variables.
}

Upvotes: 1

Related Questions