I want to iterate over the environment keys and print a list of these items.
views:
104answers:
2
+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
2009-12-16 18:50:43
thanks for that. how about if i want to expand the variables?
codeninja
2009-12-21 18:30:46
+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
2009-12-21 15:28:49