VBS Read and Set Environment Variables

Below are a few basic examples of how to read and set Environment Variables using a VBS Script.

Create a new Permanent System Environment Variable

The below example creates a new permanent System Environment variable called “test” with the value “Hello World!”

If you get an Access Denied message on Vista the fault of “User Account Control”

Set objShell = CreateObject("WScript.Shell")
Set objEnv = objShell.Environment("SYSTEM")
 
objEnv("test") = "Hello World!"

Create a new Permanent User Environment Variable

The below example creates a new permanent User Environment variable called “test” with the value “Hello World!”

If you get an Access Denied message on Vista the fault of “User Account Control”

Set objShell = CreateObject("WScript.Shell")
Set objEnv = objShell.Environment("USER")
 
objEnv("test") = "Hello World!"

Reading a System Environment Variable

The below example shows how to read a System Environment Variable called “test”

Set objShell = CreateObject("WScript.Shell")
Set objEnv = objShell.Environment("System")
 
wscript.echo objEnv("test")

Reading a User Environment Variable

The below example shows how to read a User Environment Variable called “test”

Set objShell = CreateObject("WScript.Shell")
Set objEnv = objShell.Environment("User")
 
wscript.echo objEnv("test")

Practical Example: Appending to the System Environment Variable “Path”

One of my more common reasons for playing around with Environment Variables

Set objShell = CreateObject("WScript.Shell")
Set objEnv = objShell.Environment("System")
 
'What we want to add
PathToAdd = "C:\Program Files\IBM\Lotus\Notes"
 
'Get the current value of Path
oldSystemPath = objEnv("PATH")
 
'Build the new Path
newSystemPath = oldSystemPath & ";" & PathToAdd
 
'Set the new Path
objEnv("PATH") = newSystemPath
 
wscript.echo "Complete"

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.