0

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) ?

1 Answer 1

1

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.
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Is there a way to get user created variables too ? Like if I create a variable like this: psShell.AddScript("$testVar = 'testk2'");, and then set environmentVariableName to testVar, and then call the command you mentioned above ? .. If I do it this way, no value for testVar is returned :(
@Ahmad Something like that: environmentVariable = psShell.AddScript("$testVar = 'testk2'; $testVar").Invoke<string>()[0];. If i understand what you trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.