Compartir a través de


How to read User and System Variables using VBScript

Quite easy!

Dim objWSH
Dim objUserVariables
Dim objSystemVariables

Set objWSH =  CreateObject("WScript.Shell")
'This actually returns all the User Variables, and you either loop through all, or simply print what you want
Set objUserVariables = objWSH.Environment("USER")
MsgBox(objUserVariables("TEMP"))

'This returns all the System Variables, and you either loop through all, or simply print what you want
Set objSystemVariables = objWSH.Environment("SYSTEM")
MsgBox(objSystemVariables("PATH"))

'Say you want to add a System or a User variable. Pretty simple, just use the object and assign the value!
objSystemVariables("I_AM_SYSTEM_VARIABLE") = "System Variable Sir!"
objUserVariables("I_AM_USER_VARIABLE") = "User Variable Sir!"

Remember, if you want to do this in classic ASP (on IIS 6), it will work only if you are running the App Pool under "Local System" or you have a custom account with Admin rights. It is not gonna work with Network Service!

Hope this helps!
Rahul

Comments

  • Anonymous
    January 10, 2007
    Great post !  However, I vaguely remember that the USER profile does not get loaded in IIS6 due to security constraints . So the "USER" environment variables are not gonna be enumerated in IIS 6

  • Anonymous
    January 10, 2007
    Honestly speaking, IMHO, playing with Environment variables in a web application is not a decent idea anyways!

  • Anonymous
    August 10, 2007
    It is a Great Post. It is vert helpful to me

  • Anonymous
    September 10, 2007
    Nice work man ur code helped me and its working properly :-)

  • Anonymous
    December 09, 2007
    In regards to saying that web apps using Env variables is not a good idea is terribly wrong.  I use HTA's in a lot of scripts that i write to automate network tasks and the use of environment variables in HTA's is not only much more standardized, but much more useful. Web apps aren't the only place these are used :)1

  • Anonymous
    December 09, 2007
    Hello Dustin, Thanks for your comment. I guess, I never said that Web apps are the only place where these variables are used. I just wanted to ensure that I am not asking folks to run application under Local System account just to read those variables. Besides, I have a difference of opinion here and would rather stick to the fact that there might be applications that use Env variables. BUT, IMHO... that's not a very good practice, specially if you end up changing the app pool identity to Local System :-) I am yet to encounter a scenario where a specific requirement cannot be achieved from a web app WITHOUT using ENV variables!

  • Anonymous
    February 28, 2008
    Thanks...  this solved my problem.

  • Anonymous
    March 06, 2008
    Thanks Our Issue got Resolved by this post...

  • Anonymous
    March 13, 2009
    Thanks man. It's really helpful