Tuesday, August 10, 2010

QTP: How to Read or Write Windows Envrionment Variables

It is easy to read and write Windows Environment Variables from QTP using VBScript. Note that this is NOT done using what is called "Environment Variables" in QTP.

Add test variable
For the sake of this post I added a environment variable to windows called "jonas123"
In Xp: In Control Panel > System > Advanced Tab > Environment Variables add a user varible and give it a value. I gave mine 'apa'

Setup
The following code gives you the basic objects for manipulating windows Environment Variables
Option explicit

'Declare Variables
Dim wScript, Shell, UserVar
'Set objects
set wScript = CreateObject("WScript.Shell")
Set Shell = wScript.Environment("User")

Read
Reading the environment variable is now easy

'Save to local variable
UserVar = Shell("jonas123")
'Now UserVar contains 'apa'
or
'Show messagebox with environment variable
msgbox Shell("jonas123")
' "apa" is displayed

Write
Writing is even easier
' Save new value to environment variable
Shell("jonas123") = "monkey"

Adding a variable
Just write to a variable that does not exist
Shell("jonas1234") = "banana"

What about system environment variables?
In your setup code just load "System" Environment instead of "User"
Set Shell = wScript.Environment("System")

No comments: