How do I print the list of registry keys in HKCU\Environment to SDTOUT using JScript (WSH)?

不想你离开。 提交于 2019-12-11 14:04:20

问题


I want to iterate over the environment keys and print a list of these items.


回答1:


You can access the user environment variables via the appropriate WshEnvironment collection; there's no need to mess with the registry:

var oShell = new ActiveXObject("WScript.Shell");
var oUserEnv = oShell.Environment("User");

var colVars = new Enumerator(oUserEnv);
for(; ! colVars.atEnd(); colVars.moveNext())
{
  WScript.Echo(colVars.item());
}

This script will output the variable names along with values (non-expanded), e.g.:

TEMP=%USERPROFILE%\Local Settings\Temp
TMP=%USERPROFILE%\Local Settings\Temp
Path=%PATH%
PATHEXT=%PATHEXT%;.tcl

If you need the variable names only, you can extract them like this:

// ...
var strVarName;
for(; ! colVars.atEnd(); colVars.moveNext())
{
  strVarName = colVars.item().split("=")[0];
  WScript.Echo(strVarName);
}

Edit: To expand the variables, use the WshShell.ExpandEnvironmentStrings method; for example:

// ...
var arr, strVarName, strVarValue;
for(; ! colVars.atEnd(); colVars.moveNext())
{
  arr = colVars.item().split("=");
  strVarName = arr[0];
  strVarValue = oShell.ExpandEnvironmentStrings(arr[1]);

  WScript.Echo(strVarName + "=" + strVarValue);
}



回答2:


When I tried the code given in the answer, I got an error on line 4. I believe it should be:

var colVars = new Enumerator(oUserEnv);


来源:https://stackoverflow.com/questions/1911488/how-do-i-print-the-list-of-registry-keys-in-hkcu-environment-to-sdtout-using-jsc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!