WScript.Shell ExpandEnvironmentStrings
Thursday, August 18, 2005
Anyway, I was using the WScript.Shell object to automate some tasks and found an interesting thing I haven’t run into or perhaps just never noticed. When I get an environment variable using the ExpandEnvironmentStrings method, if the variable doesn’t exist it will return what you passed in to it.
Dim objShell : Set objShell = CreateObject("WScript.Shell")
MsgBox objShell.ExpandEnvironmentStrings("%MyPath%")
Set objShell = Nothing
If the %MyPath% environment variable exists on your machine it will show the value stored in the variable. (I ran into this running the same script on all versions of Windows.) If it doesn’t exist it will show %MyPath%. That was wreaking havoc on my little script.
So, I just perform a simple check afterwards to verify the value exists.
Dim objShell : Set objShell = CreateObject("WScript.Shell")
Dim sValue
Dim sVarName
sVarName = "%MyPath%"
sValue = objShell.ExpandEnvironmentStrings(sVarName)
If sValue <> sVarName Then
MsgBox sVarName & " = " & sValue
Else
MsgBox sVarName & " does not exist"
End If
Set objShell = Nothing