Techno Logica


Thursday, October 9, 2008

QTP Programming - Set & Remove Environment Variables

The Below Code Sets Environment Variables:

Dim
objWshShell, WshEnv, strEnvName, strEnvValue

strEnvName = "User_Name"
strEnvValue = "Sunny"

' create the WScript.Shell object
Set objWshShell = CreateObject("WScript.Shell")

' access the User Environment property
Set WshEnv = objWshShell.Environment( "User" )

' create and set the custom variable
WshEnv( strEnvName ) = strEnvValue


Remove a specified User environment variable

' access the User Environment property
WshEnv.Remove sVarName

3 comments:

Anonymous said...

This is quite cool, but does not work.
Given that you have not used your variables as expected, and the WScript Environment already includes "User" you can edit this variable.
I cannot however get it to create a new environment variable at all via your script.

Anonymous said...

A little research found this:
http://technet.microsoft.com/en-us/library/ee156595.aspx

And this:
http://msdn.microsoft.com/en-us/library/fd7hxfdd(v=vs.85).aspx

It seems you cannot add any variable with this, only those designated to the collection.
You can add any value you like to the "User" environment variable, but it seems a pretty unclean way to do it and surely there is another way...

Anonymous said...

Ended up with this as a working model:
http://technet.microsoft.com/en-us/library/ee156595.aspx

Option Explicit

'Create and populate the environment variable
Call EnvVarAdd("HPPartner","JDS Australia"))
'Use it wherever you like
Msgbox "Outside the function: " & EnvVarUse("HPPartner")
'When you are done with it, remove it...
Call EnvVarRemove("HPPartner")
Msgbox "Should return no value: " & EnvVarUse("HPPartner")


Function EnvVarAdd(sEnvName,sEnvValue)
Dim oShell,oEnv
Set oShell = CreateObject("WScript.Shell")
Set oEnv = oShell.Environment("User")
oEnv(sEnvName) = sEnvValue
End Function

Function EnvVarUse(sEnvName)
Dim oShell,oEnv
Set oShell = CreateObject("WScript.Shell")
Set oEnv = oShell.Environment("User")
EnvVarUse = oEnv(sEnvName)
End Function

Function EnvVarRemove(sEnvName)
Dim oShell,oEnv
Set oShell = CreateObject("WScript.Shell")
Set oEnv = oShell.Environment("User")
oEnv.Remove sEnvName
End Function