Overloading Methods and More in VBScript - Using the Overloaded Constructor
(Page 3 of 4 )
Function PingTest(varTarget)
If IsArray(varTarget) Then
'Test against an array
PingTest = arrResults
Else
'Test against a string
PingTest = arrResults
End If
End Function
You can see here that I’ve changed the logic of this function a bit. Namely, I’m using the IsArray function along with a simple IF statement to determine exactly what type of data was passed into the function. Now I can insert the code to handle each case.
Function PingTest(varTarget)
If IsArray(varTarget) Then
arrResults = Array()
For i = 0 To UBound(varTarget)
ReDim Preserve arrResults(i)
strComputer = "."
Set objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")
Set colPings = objWMIService.ExecQuery("Select * From Win32_PingStatus " _
& "Where Address = '" & varTarget(i) & "'")
For Each objPing In colPings
If objPing.StatusCode = 0 Then
arrResults(i) = "Success"
Else
arrResults(i) = "Failure"
End If
Next
Next
PingTest = arrResults
Else
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 If
End Function
Okay, this looks pretty complicated, but it’s really not as bad as it seems. If you look closely, each branch of this IF block is identical to my original function, with one minor change in the If portion. Here I’ve wrapped my function code inside of a For Each loop that moves through each IP address in the supplied array. Each test’s result is added to the output array before it is returned by the function. The Else portion remains the same as in the original function because it uses a string parameter as originally intended.
Okay, so now that we’ve created an “overloaded” constructor, how do we use it in our scripts? Well, let’s take a look. First, let’s see it the way we wrote it the first time.
arrResults = PingTest("127.0.0.1")
WScript.Echo arrResults(0)
This example performs a ping test against the local loopback address. It should simply print “Success” on the screen.
arrTests = Array("127.0.0.1", "192.168.0.0", "192.168.0.100")
arrResults = PingTest(arrTests)
For i = 0 To UBound(arrTests)
WScript.Echo arrTests(i) & ": " & arrResults(i)
Next
Here I’m supplying an array of strings to test against. The PingTest function still returns an array of results so it’s a simple matter of iterating through that array. Each element in the results array matches the same element in the tests array. Thus, the result for the test on arrTests(0) can be found in arrResults(0).
Next: Implementing Optional Parameters >>
More Windows Scripting Articles
More By Nilpo