Overloading Methods and More in VBScript - Information Overload
(Page 2 of 4 )
Despite the fact that constructor overloading has been removed from VBScript, you can simulate much of its functionality. This involves determining the type of data being passed into the function and responding accordingly. From my experience, this is most often useful when you have a function that can be performed against a single target or against multiple targets in an array. Let’s consider an example.
Function PingTest(varTarget)
arrResults = Array()
ReDim Preserve arrResults(i)
strComputer = "."
Set objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")
Set colPings = objWMIService.ExecQuery("Select * From Win32_PingStatus " _
& "Where Address = '" & varTarget & "'")
For Each objPing In colPings
If objPing.StatusCode = 0 Then
arrResults(i) = "Success"
Else
arrResults(i) = "Failure"
End If
Next
PingTest = arrResults
End Function
This code sample defines a function called PingTest. It accepts a string input (an IP address) and performs a ping test. The result of that test is returned in an array.
I’ve chosen to return results in an array, because I’ll be adding multiple results later in this article.
The exact mechanics of this function are irrelevant as far as our topic is concerned, so I’ll be brief. The IP address (as a string) is used in a query to the Win32_PingStatus WMI class. This class returns a status code that indicates the result of a ping test. We then return the word “success” or “failure” based upon that status.
All is well. However, this function can only be run against a single machine at any given time. What if we wanted to supply an array of targets and receive all of the results at the same time? An overloaded constructor would be nice. But since we cannot create one, let’s take a look at what we can do instead.
As I mentioned earlier, all variable types in VBS are treated as type Variant. This means that our function doesn’t particularly care whether we provide a string or an array as a parameter. It’s only written to work with a string. Thus, we can pass any data type we wish. All we need to do is rewrite our function to work with different data types.
Next: Using the Overloaded Constructor >>
More Windows Scripting Articles
More By Nilpo