VbScript Environment, System Variables Reading

At times, when programming with vbscript, a programmer will want to read an existing environment variable.

This can be accomplished by accessing the Windows Script
Host via VBScript and making use of the shell object

The program example below will walk you through the steps necessary to accomplish this task and give you a real world example to learn from.


Step 1

1. Create a User Environment Variable
Create a user environment variable by right-clicking on "My Computer", selecting Properties - Advanced tab - Environment Variables and under User variables select New. This will open a New User Variable window. For Variable name:, type test. For Variable value:, type your name and select OK.

2. Open Notepad
Go to Start - All Programs - Accessories - Notepad
Save your file as C:\Temp\ReadEnvVar.vbs
#
Step 3

3. Copy Code
Copy and Paste the following code into Notepad.

'**************************************************************
Option explicit

'Declare Variables
Dim WshShl, Shell, UserVar

'Set objects
Set WshShl = WScript.CreateObject("WScript.Shell")
Set Shell = WshShl.Environment("User")

'Read variable
UserVar = Shell("Test")

'Output value to msgbox
WScript.Echo "Your name is " & UserVar & "!"

'Cleanup Objects
Set WshShl = Nothing
Set Shell = Nothing

'Exit Script
WScript.Quit()
'**************************************************************
Save your file and exit Notepad

4.Run Script

Browse to C:\Temp\ReadEnvVar.vbs using My Computer or Explore, depending on what you're use to.
Double-click on ReadEnvVar.vbs. You should get a message box as shown stating your name.

Select "OK"
 
4.      If you prefer to read a System environment variable, replace this line in your script
   
   Set Shell = WshShl.Environment("User")
      With this line
      Set Shell = WshShl.Environment("System")

      Replace this line
      UserVar = Shell("Test")
      With this line.
      UserVar = Shell("Insert system variable you want to read here")

      Replace this line
      WScript.Echo "Your name is " & UserVar & "!"
      With this line
      WScript.Echo UserVar

      So your vbscript makes sense, you may also want to replace the UserVar variable with SysVar, but your script should function just fine without this change.
  
      Step 5
  You've written a VBScript capable of reading a user or system environment variable.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.