How to Read a User/System Environment Variable Using VBScript
When programming with VBScript, you may need to read an environment variable. This can be accomplished by accessing the Windows Script Host using VBScript and making use of the shell object. The best way to learn how to access environment variables is with a real world example that walks you through the steps.
Instructions
-
-
1
Create a user environment variable. Click on the Windows orb in the lower left corner of your desktop to open the Start menu. Right-click on "Computer" and then click “System Properties.” Click “Advanced System Settings.” A dialogue window opens. Click the “Environment Variables” button in the lower right corner. Click "New" just below User Variables. Type “test” in the “Variable Name” field” and type your name in the “Variable Value” field. Click the “OK” button at the bottom of the window.
-
2
Open Notepad by clicking “Start” and typing “notepad” in the search box. Click on the application when it appears in the search results above. Create a new document and save it as “C:\Temp\ReadEnvVar.vbs”.
-
-
3
Copy and paste the following code into Notepad:
Option explicit
'Declare Variables
Dim WshShl, Shell, UserVar'Set objects
Set WshShl = WScript.CreateObject("WScript.Shell")
Set Shell = WshShl.Environment("User")'Read variable
UserVar = Shell("Test")'Output value to msgbox
WScript.Echo "Your name is " & UserVar & "!"'Cleanup Objects
Set WshShl = Nothing
Set Shell = Nothing'Exit Script
WScript.Quit() -
4
Save your file and exit Notepad.
-
5
Run the script. Browse to “C:\Temp\ReadEnvVar.vbs” and double-click on the file. A message box should pop up displaying your name. Select "OK."
-
6
Read a system environment variable by replacing this line in your script –
Set Shell = WshShl.Environment("User") – with the following line:Set Shell = WshShl.Environment("System")
Replace this line – UserVar = Shell("Test") – with:
SysVar = Shell("Insert system variable you want to read here")
Finally, replace this line – WScript.Echo "Your name is " & SysVar & "!" – with the following:
WScript.Echo UserVar
-
7
Save your script and exit Notepad. You now have a VBScript capable of reading a user or system environment variable.
-
1
Tips & Warnings
When working with a VBScript (.vbs) file, right-click on the file and choose "Edit" to modify it; otherwise, you will run the script by double-clicking on it.
When working with vbscript(.vbs) files you'll want to right-click on them and choose Edit to modify them, otherwise you will run the script.