Writing Portable Scripts in WSH - Scripting Environmental Variables
(Page 2 of 4 )
WSH provides two ways to handle environmental variables natively. Let’s take a look at how to implement them in your scripts.
WSH provides us with the WshEnvironment object. This is a read/write collection that contains the environmental variables. You must use the WshShell object’s Environment property to access this object.
Set WshShell = CreateObject("WScript.Shell")
Set colEnvVars = WshShell.Environment
For Each objVar In colEnvVars
WScript.Echo objEnv
Next
The above example lists all of the environmental variables found in the WshEnvironment collection. Let’s take a look at the properties and methods available to the WshEnvironment object.
Properties
object.Item(name)
object.length
Methods
object.Count
object.Remove name
You can use the Item property to return the contents of a specific environmental variable. The length property and the Count method both perform the same function and return the number of items in the collection. Finally, the Remove method deletes a specified item.
You may have noticed that the list of variables in the last example seemed a bit short. For example, the common %systemroot% variable wasn’t there. You may be wondering why.
There are three types of environmental variables: System, User, and Process. By default, the Environment property only returns those in the System list. However, you can specify which ones are returned. On Windows NT systems you can see the entire list in the following manner.
Set WshShell = CreateObject("WScript.Shell")
Set colEnvVars = WshShell.Environment("Process")
For Each objVar In colEnvVars
WScript.Echo objEnv
Next
There, now that’s better. So let’s take a little closer look at what we can do with environmental variables. We’ll begin by learning how to create our own.
Set WshShell = CreateObject("WScript.Shell")
Set colEnvVars = WshShell.Environment("System")
colEnvVars("MyVariable") = "This is my variable"
WScript.Echo colEnvVars.Item("MyVariable")
colEnvVars.Remove "MyVariable"
To add our own variable, all we need to do is add an item to the Environment collection. This is done simply by specifying the new item name and its initial value as with any collection.
Our script then goes on to display the newly created variable by checking it with the Item property. Finally, we delete it with the Remove method. That wasn’t so hard, was it?
Now that you know how to manipulate variables, let’s take a look at what they can be used for.
Next: Using Environmental Variables >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer