Script Tips
Recycling: It's Good for the Script
Modularize your VBScripts with subs and functions.
This is the second column in which I'll continue to look at several confusing
core techniques in VBScript. This time, I'll focus on VBScript Subs and
Functions, which are a great way to modularize your code. But, keep in
mind that there are some rules about how to use them. Here's a perfect
example:
Function TestPing(sName)
Dim cPingResults, oPingResult
Set cPingResults = _
GetObject("winmgmts://./root/cimv2").ExecQuery(_
"SELECT * FROM Win32_PingStatus WHERE Address = '"_
& sName & "'")
On Error Resume Next
For Each oPingResult In cPingResults
If oPingResult Is Null Then
TestPing = False
ElseIf oPingResult.StatusCode = 0 Then
TestPing = True
Else
TestPing = False
End If
Next
End Function
Here what this function does:
- It declares an argument, strComputer, which will hold the function's
input. The function doesn't rely on any data apart from this argument,
thus making the function entirely self-contained.
- The function returns a result, either True or False, by setting the
function's name equal to whatever value is to be returned.
- The function doesn't reference any variables apart from those declared
within the function itself.
- The strComputer argument works like a variable, but doesn't need to
be declared using the Dim keyword-it's declared as a part of the function
itself.
By the way, this will only run on WinXP and Win2003 boxes, and it'll
give you a True or False if the computer you specify that it's pingable
or not. Use this function like this:
If TestPing("server1") Then
'is available
Else
'is not pingable
End If
By keeping the TestPing() function self-contained, it can be easily pasted
into any script where you need to use it. That's the real goal of Subs
and Functions: to modularize and encapsulate code so that it can be more
easily reused. Reusing code saves time, so it's a good habit to practice.
About the Author
Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is Curriculum Director for IT Pro Content for video training company Pluralsight. Don is also a co-founder and President of PowerShell.org, a community dedicated to Microsoft’s Windows PowerShell technology. Don has more than two decades of experience in the IT industry, and specializes in the Microsoft business technology platform. He’s the author of more than 50 technology books, an accomplished IT journalist, and a sought-after speaker and instructor at conferences worldwide. Reach Don on Twitter at @concentratedDon, or on Facebook at Facebook.com/ConcentratedDon.