简体   繁体   English

如何从远程 powershell C# 代码中获取环境变量值?

[英]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.我正在通过 C# Powershell 库连接到远程机器,并希望通过 C# 代码从该机器获取环境变量。 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 :我得到一个Specified method is not supported异常......进一步钻探,我看到SessionStateProxy具有由于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 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)?那么我如何通过 C# 远程 powershell 代码获取环境变量值,而无需简单地运行远程脚本到 output 值或其他东西(我不想要什么正确的方式)?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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