Tag : scripting

Learning Visual Basic Scripting Variable Scope

My experiences with VBS Scripting.

 

You can’t be a System Admin in the School systems for very long without using a vbs script to get something done.  We use a wide variety of scripts to help maintain our control over the hundreds of computers that we are faced with. I have even used scripts to delete  backdoor admins that where created by the previous techs.

{code lang:vb id:8}{/code}

This script is a very simple representation of what a VBS script can do.  Running this as a computer startup script will remove and trace of the specified user.

 

I have found that VBS scripts can be very forgiving in their usage.  An example of this is in the script above.

strComputer =”.”

This line in most languages would need to be declared before you say it is equal to anything.  VBS allows you to call a variable (strComputer) without specifying what it will be used for.

Another example of this same script seen here is written with several differences. 

 

{code lang:vb id:9}{/code}

This code does the exact same thing, but it is more formal in that everything is declared.

The line:

Option Explicit

means that it will only run if all the variables are called.  You see this on line 2

Dim strComputer, strUser

where Dim is calling strComputer and the comma separates the variables. You could see it called like this:

Dim strComputer
Dim strUser  

Variable Scope

Another reason to declare variables at the beginning of the script is to define scope.  What? OK if you have one object like strComputer that you need to run in two functions that will need to be defined outside the functions.

 

{code lang:vb id:10}{/code}

In this example there are three variables.  The first is varNew and the second and third have the same name called testVar.  Because testVar only exists within each function – they are different.

If you run the script you would get  Image Right:

 

Functions

VarScope

The next section of code calls a function  runScript()  and the has WScript.Quit

the runScript() tells the computer to find the function runScript() and execute its code block.

WScript.Quit tells the program to exit the script.

 

 

I will post more tutorials later on how to start scripting with VBS scripts.