The VBScript Network and Systems Administrator's Cafe:

Subroutines

Aug 1 2008   2:32AM GMT

VBScript Statements: Explanation of the Sub Statement



Posted by: Jerry Lees
VBScript, Subroutines, VBScript Statements, Sub, Sub Statement

The VBScript statement Sub allows you to create a section of code that can be reused over and over, called a subroutine. It also allows you to name this section of code and refer to it by name, rather than typing it in multiple times.

Subroutines can optionally have parameters associated with them, but they must complete all their work in the subroutine because they can not return any values back to the portion of the program that called them.

Sub routines start with a declaration of the name and parameters and end with a “End Sub” statement. An example subroutine would look like so:

Sub AddNumbers (x, y)
    Wscript.Echo (x+y)
End Sub

To call this subroutine from your script you would simply place the following code elsewhere in your script:

AddNumbers 2, 4

(Notice that parenthesis were not used when calling the subroutine.)

Mar 27 2008   3:03PM GMT

Rebooting or Shuttingdown a Server Remotely with VBScript



Posted by: Jerry Lees
Development, VBScript, Functions, Subroutines

In this installment I’d like to share with you a scriplet I developed out of frustration with not having found this information anywhere else.

 On occasion you need to reboot a server, sure you can do it by logging in or by the shutdown command on windows XP. Heck you can even do it with the Windows 32 API calls in C++! However, sometimes you don’t want to be up and awake when you need to reboot a server. Plus, you might want to have some sort of logic behind it like instead of rebooting every night blindly you might want to check to see is a process is running (like a windows service) and stop it in a controlled manner before rebooting the system– we’ve all go those one off servers that have some weird application that needs fiddling with before you reboot, or atleast the lore at the office says you need to do something first. Right?

Well, I recently had such a situation and became frustrated that I couldn’t reboot a server cleanly with in a script without first executing from within the script, as a child process, a batch file to do the reboot for me. Sure it works… and the main reason I didn’t like it was it wasn’t as sophisticated as I’d like. But another problem is that I would have no real way of knowing what the outcome of the reboot process– in other words, I wouldn’t be able to handle the fact that the reboot didn’t occur or the batch file had an error because windows would have returned only that the command prompt executed and the batch was ran.

In two previous posts, I’ve provided information on Functions, WMI, and Methods to lead up to this topic. If you missed them you might go back and read the quickly so you’ll be up to speed. The posts are:

Working with Subroutines and Functions in VBScript
Using Windows Management Interface (WMI) to Make Your Life Easy.

 In the following script, I create a function called Reboot that uses WMI to create a connection to a server name you pass to it (Note: to protect you I have set the call to reboot() in the script to use “.”, which is the local machine. Change “.” to “ServerName” to reboot a specific remote machine. In other words… run this code unchanged and your desktop will reboot in the next 30 seconds.)

Reboot(”.”)

Function Reboot(StrSrv)
   Set objWMIService = GetObject(_
   ”winmgmts:{impersonationLevel=impersonate,authenticationLevel=Pkt,(Shutdown)}!\\”_
   
& StrSrv & “\root\cimv2″)
   Set colItems = objWMIService.ExecQuery(”Select * from Win32_OperatingSystem”,,48)
   For Each objItem In colItems
        WScript.Echo objitem.Reboot
   Next
End Function

This is a really useful scriptl function, when combined with other pieces of code to gather performance monitor counters (later I’ll post some code examples on this) you could reboot a server if the non-paged pool memory reaches a point where the system is probably going to lock up due to a leaky app or driver… this was my issue I solved with vbscript. 

As always, this code works perfectly. However, sometimes the formatting of the blog breaks the code if you copy and paste it into your editor. So, if you’d like to not type or troubleshoot any syntax errors due to the copy and paste problems– I’ve provided the code for download, plus example output files  from my final tests for you. You’ll find the code and other files available for download from my website’s (www.websystemsadministration.com) File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!

Extra credit: Can you figure out what the following part of the code does?{impersonationLevel=impersonate,authenticationLevel=Pkt,(Shutdown)}


Mar 20 2008   6:26PM GMT

Explanation: Working with Subroutines and Functions in VBScript



Posted by: Jerry Lees
Development, VBScript, DataManagement, Functions, Subroutines

I just realized in my haste to get out a piece of code celebrating the XBOX 360 contest, I negected to give a proper answer for our discussion on subroutines and functions in a vbscript.

In this installment, we’ll explain how to build a function and a subroutine a bit better. First, remember functions and subroutines are basically smaller pieces of your script — they essentially are the work horse of your script.

They both get passed information when they are called and preform their work according to what the information they have been given. These values passed can literally be anything you need to make the subroutine or function work but are generally only what the function needs to preform it’s work. You can reference the whole blog entry here.

Basically, you can build a subroutine like so:

Sub MySub(myvariable)

‘… your code here

End Sub

You would call this subroutine like so:

MySub XVariable
-Or-
MySub 10
-Or-
MySub “This Value”

Notice that I didn’t use Parenthesis, you don’t when calling a subroutine. The value you pass the subroutine can be variable (XVariable), a literal number (10), a string (”This Value”), or any other specific item you need to pass into the subroutine– even an array, providing you’re expecting the variable type!

Functions are the exact same as subroutines except in the label when you create them and in that they can return a value.

To create a function you:

Function MyFunction

‘… your code here

MyFunction = X

End Function

To call a function you use parenthesis, unlike a subroutine, like so:

X = MyFunction (XVariable)
-Or-
X = MyFunction (10)
-Or-
X = MyFunction (”This Value”)

Notice the line in red? This is the line of the function that does the magic of returning a value! It essentially works on the premise that the function name is a variable in the function that is always there. at the end of the function’s work the value is passed back to the calling routine as the return value– and it does this automatically.

Also notice how I changed the line to call a function? I placed a variable, X, in front of the function and set X equal the return of the function. You can also use a function in comparisons like so:

If Myfunction(10) = 1 then
‘your code here
end if

So, we’ve covered the creation and calling of a subroutine, the creation and calling of a function, how to assign a value to the return of a function, and how to use the return from the function.

From this point, you can use your imagination for when and where to use functions and subroutines!


Mar 10 2008   3:33PM GMT

Working with Subroutines and Functions in VBScript



Posted by: Jerry Lees
Development, VBScript, Functions, Subroutines

In this installment, we’ll discuss the advantages of using Subroutines and Functions in your script rather than using a all-in-one script that runs from start to finish. I’ll only give a breif over veiw of subroutines and function, but more information on them can be found in the VBScript User’s guide and Language reference.

First, Functions and subroutines are basically smaller pieces of your script. They are generally a part that completed a specific task in the script and are very helpful in accomplishing the following:

      Creating reusable code to use in other scripts without having to re-write the code
      Making your code more readable
      Using the same set of code multiple times in the same script without a loop of some type.
      Helpful in debugging a script and disabling a section of code
      Helpful in organising the logic of the script into smaller bite sized pieces

They essentially are the work horse of your script. In General, I try to keep all the logic of a script in a Function or a subroutine– that way If I have to make modifications I’m only going to at worst break a small (but possibly important) piece of the script. Remember, Subroutines and functions can call other subroutines and functions– so they are not limited to just being used within your main script– Infact, a single function or subroutine can call itself! This is outside the scope of this posting, but is called a recursive funtion or subroutine.

They both get passed information when they are called and  preform their work according to what the information they have been given. These values passed can literally be anything you need to make the subroutine or function work. These values are generally only what the function needs to preform it’s work. For example:

Say you need to calculate the price you pay for an item at the store, so you can have exact change in cash. Think about what information you need. You just need the price of the item and any sales tax on the item, you don’t need anything else like where the store is or who the cashier is. That’s essentially what a subroutine is!

Now, Functions and subroutines are VERY similar. In fact, there is only one major difference in the two of them. They both offer a way to better organize your code into bite sized chunks, create re-usable sections that are easier to manage and modify, and they both preform a very specific task.

The only difference is that a subroutine does it’s work and deals with it’s result inside itself without communicating the end result back to the routine that called it to run.  So it’s kind of a loner… just does it’s work and doesn’t bother anyone else with the details or the result. This is useful for file or screen I/O where you don’t need any information returned to you. Basically, it’s a script all in itself. In our earlier example the subroutine would need to print out or do something with the values calculated and no other area of the program would be aware of where the result.

A function on the other hand will communicate back to the calling routine some value… possibly the result of some calculation, like our total price of the item, or an error condition for the calling routine to process and deal with in a manner that is fitting for the situation.

In my example below I provide you with both examples of a subroutine and a function to add two numbers together. Notice that when I call the subroutine in vbscript I do not use parenthesis around the values I pass to the routine, but with a function I do use them. This is just simply the way it is done in VBScript and will result in an error if your do it the other way around.

Option Explicit
Dim ReturnValue

TestSub 2,2 ‘ subroutine call– notice no ( ) around the two values!?!?!
ReturnValue = TestFunction (2,2) ‘function call– notice the ( ) around the two values… plus some thing else!
WScript.Echo “Function returned: ” & ReturnValue

‘ end of main code

Function TestFunction (Value1, Value2)
‘ Function to add two numbers and RETURN the value to the calling routine.

Dim Sum
 Sum = value1 + Value2
 WScript.Echo (”Functions: All your work is done here and used here, but can be sent back to the main script.”)
 WScript.Echo Value1 & ” + ” & Value2 & ” = ” & Sum

TestFunction = Sum

End Function
Sub TestSub (Value1, Value2)
‘ Subroutine to add two values together… notice all the work is done and used here?

Dim Sum
 Sum = value1 + Value2
 WScript.Echo (”Subroutines: All your work is done here and used here.”)
 WScript.Echo Value1 & ” + ” & Value2 & ” = ” & Sum

end Sub

Play with this code… see if you can figure it out. In a few days I will explain it in a bit of better detail. Take note of how I build the function, subroutine, and see if you can figure out the line that does the magic of returning the value from the function. 

Extra Credit: Did you notice the line that had option explicit and the lines that have Dim in them? What do they do? Post a comment and I’ll let you know in a few days.