Windows Vista keeps track of a number of environment variables
that hold data such as the location of the Windows folder, the location
of the temporary files folder, the command path, the primary drive, and
much more. Why would you need such data? One example would be for
accessing files or folders within the main Windows folder. Rather than
guessing that this folder is C:\Windows, it would be much easier to just query the %SystemRoot%
environment variable. Similarly, if you have a script that accesses
files in a user’s My Documents folder, hard-coding the username in the
file path is inconvenient because it means creating custom scripts for
every possible user. Instead, it would be much easier to create just a
single script that references the %UserProfile% environment variable. This section shows you how to read environment variable data within your scripts.
The defined environment variables are stored in the Environment collection, which is a property of the WshShell object. Windows Vista environment variables are stored in the "Process" environment, so you reference this collection as follows:
WshShell.Environment("Process")
Listing 1 shows a script that runs through this collection, adds each variable to a string, and then displays the string.
Listing 1. A Script That Displays the System’s Environment Variables
Set objWshShell = WScript.CreateObject("WScript.Shell") ' ' Run through the environment variables ' strVariables = "" For Each objEnvVar In objWshShell.Environment("Process") strVariables = strVariables & objEnvVar & Chr(13) Next WScript.Echo strVariables
|
Figure 1 shows the dialog box that appears (your mileage may vary).
If you want to use the value of a particular environment variable, use the following syntax:
WshShell.Environment("Process")("strName")
WshShell | The WshShell object |
strName | The name of the environment variable |
Listing 1 shows a revised version of the script from this Listing to create a shortcut. In this version, the Environment collection is used to return the value of the %UserProfile% variable, which is used to contrast the path to the current user’s Desktop folder.
Listing 1. A Script That Creates a Shortcut File Using an Environment Variable
Set objWshShell = WScript.CreateObject("WScript.Shell")
strUserProfile = objWshShell.Environment("Process")("UserProfile")
Set objShortcut = objWshShell.CreateShortcut(strUserProfile & _
"\Desktop\Edit BOOT.INI.lnk")
With objShortcut
.TargetPath = "C:\Windows\Notepad.exe "
.Arguments = "C:\Boot.ini"
.WorkingDirectory = "C:\"
.Description = "Opens BOOT.INI in Notepad"
.Hotkey = "Ctrl+Alt+7"
.IconLocation = "C:\Windows\System32\Shell32.dll,21"
.WindowStyle = 3
.Save
End With