简体   繁体   中英

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 :

在此处输入图像描述

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

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM