Writing Portable Scripts in WSH - Using Environmental Variables
(Page 3 of 4 )
Environmental variables were intended to be used by applications for cross-platform compatibility. With that in mind, they were designed to house important information about the operating system. Most commonly they are used to house common folder paths.
There are many ways in WSH to determine the currently logged on user. Most often you would probably use the WshNetwork object or WMI, but the next example shows a very simple method using Environmental variables.
Set WshShell = CreateObject("WScript.Shell")
Set colEnvVars = WshShell.Environment("Process")
strUser = colEnvVars.Item("UserName")
You can also combine environmental variables with other methods. The next example also uses the FileSystemObject to connect to the current user’s desktop.
Set objFso = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
Set colEnvVars = WshShell.Environment("Process")
strDrive = colEnvVars.Item("HomeDrive")
strProfile = colEnvVars.Item("HomePath")
strDesktop = strDrive & strProfile & "Desktop"
Set objDesktop = objFso.GetFolder(strDesktop)
WScript.Echo objDesktop.Path
I’d like to show you one more way that WSH makes using environmental variables easy. Many times you’ll encounter environmental variables in path strings. You might see something like this:
%systemroot%System32Explorer.exe
The above path, of course, refers to the Explorer.exe program file. Suppose for a second that you encounter this path in one of your scripts. How would you handle that?
You could parse the string and poll the variable in the WshEnvironment collection and then put the string back together. Perhaps something like this:
strPath = "%systemroot%System32Explorer.exe"
Set WshShell = CreateObject("WScript.Shell")
Set colEnvVars = WshShell.Environment("Process")
x = InStr(1, strPath, "%")
y = InStr(x + 1, strPath, "%")
strVar = Mid(strPath, x + 1, y - x - 1)
strPart = Mid(strPath, y + 1, Len(strPath) - y)
strVar = colEnvVars.Item(strVar)
WScript.Echo strPath
WScript.Echo strVar & strPart
Basically, I’ve used a bunch of string manipulation to extract the variable name and then find the path associated with that variable. Then I piece it all together.
But look at all that code! Could you imagine having to write that every time? How much more code would it take if there was more than one variable in our string?
Luckily, WSH’s WshShell object makes things much easier. It provides the ExpandEnvironmentStrings method that does all of the work in the above code for us.
Set WshShell = CreateObject("WScript.Shell")
strPath = "%systemroot%System32Explorer.exe"
WScript.Echo WshShell.ExpandEnvironmentStrings(strPath)
That’s much easier now isn’t it?
Next: Using Special Folders >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer