在.NET中获取远程机器上环境变量的真实值

7

我正在尝试获取环境变量实际值
以下是我的代码:

string query = string.Format("Select VariableValue From Win32_Environment Where Name = '{0}'", variableName);

using (var searcher = new ManagementObjectSearcher(query))
using (ManagementObject result = searcher.Get().Cast<ManagementObject>().FirstOrDefault())
{
    if (result != null)
    return Convert.ToString(result["VariableValue"]);
}

那样做没问题,但问题在于:将“windir”作为名称传递会获取“%SystemRoot%”作为值。我真正想要的是实际路径,即“C:\Windows”。
我尝试使用递归来获取“SystemRoot”的值,但没有找到匹配项。
我该如何确保返回真实值?谢谢!

2
为什么%SystemRoot%不可接受?如果您将其放入资源管理器窗口中,您将转到Windows的安装目录。因为在理论上,%SystemRoot%可能是D:\ Windows\。 - Security Hound
可能是如何使用.NET远程扩展环境变量?的重复问题。 - VVS
@ Ramhound: 我正在编写一个使用 Win32_Process.Create 在远程机器上运行命令的方法。环境变量似乎无法被识别,所以我想自己替换它们。如果有办法能够自动识别它们,那也能解决我的问题。 - David
4个回答

2

对于类似于 %SystemRoot%系统路径变量,没有方便的方法。

您必须通过读取相应的注册表值来查找这些值。以下是一些这些系统变量的(不完整)列表:

  • %SystemRoot%:

    HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRoot

    select windowsdirectory from Win32_OperatingSystem
  • 可以通过检查 %SystemRoot% 来确定 %SystemDrive%

%AppData% 这样的变量是用户相关的,并且在

HKEY_USERS\<user SID>\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\AppData
下找到。


这会为我获取%SystemRoot%,但不包括**%ProgramFiles%**或其他变量。我想我正在寻找Environment.GetEnvironmentVariable的远程版本。 - David
1
@David:没有远程版本。另一种选择是通过在远程机器上启动程序来远程执行Environment.GetEnvironmentVariable,例如。 - VVS

1

我知道这最多算是创意,但这似乎是最简单的解决方案:
可能开销太大了吗?

        using (var process = new Process())
        {
            process.StartInfo.FileName = @"C:\PsTools\PsExec.exe";
            process.StartInfo.Arguments = @"\\machineName cmd /c echo " + environmentVar;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            return process.StandardOutput.ReadToEnd();
        }

太多的开销也许?完全不是。特别是与追踪递归变量解决问题的兔子洞相比:%ComSpec% = %SystemRoot%\System32\cmd.exe。真是一场噩梦。当我看到你的答案时,我差点放弃了。好技巧。 - InteXX

0

你不能使用Win32_Environment来实现这个,但是你可以使用远程注册表。

RegistryKey environmentKey = RegistryKey.OpenRemoteBaseKey(
      RegistryHive.LocalMachine, "\\server");
RegistryKey key = environmentKey.OpenSubKey(
      @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", false);
string value = (string)key.GetValue("System");

-2

使用 Environment.GetFolderPath(Environment.SpecialFolder.System)


2
问题标题说的是在远程机器上。 - TheCodeKing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接