views:

104

answers:

2

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

+1  A: 

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);
}
Helen
thanks for that. how about if i want to expand the variables?
codeninja
+1  A: 

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);
Nathaniel Mishkin
Right. Fixed that, thanks.
Helen