The VBScript Network and Systems Administrator's Cafe

April 17, 2008  8:52 PM

Creating text files using the Scripting.FileSystemObject with VBScript

Jerry Lees Jerry Lees Profile: Jerry Lees

Well, I didn’t expect the cat to get out of the bag quite so quickly! (Congratulations go out to Stoinov for getting the correct answer I was thinking of so very quickly!) So while he’s been sleeping during his night, which seems to be my day… I thought I’d throw together a quick “Write a text file” script together for you all. (A little trivia for you all in the United States, that I found hard to believe when I learned it… VBScript, and VB for that matter, is in English regardless of where you are in the world. If you’re on a Japanese system writing VBScript, your using the same language as us folks in the United States. Talk about portable code!)

Back to the matter at hand, this script doesn’t do anything terribly spectacular– by itself. All it does is opens (or creates) a text file named what you call it where you specify. The heart of the script is the WriteTextFile () function, which accepts two pieces of data; a full path to a file name and the data you want to write. That’s it! But—- this function will let you write logs, CSV (Comma Separated Value) files or any other form of text file from any type of script for which you choose to use it!

A quick little note on the access method I hard coded into the script. You  will notice three constants used ForReading, ForWriting, and ForAppending these are there so you could change the mode easily without having to go to the documentation for the OpenTextFile Method of the Scripting.FileSystemObject and figure out what numbers to use to change the access method. you simply just need to change the access method from ForReading on the OpenTextFile line of the script to accomplish this task. An excerpt of the Microsoft documentation for the values and descriptions are listed below, for your reference.

Constant Value Description
ForReading 1 Open a file for reading only. You can’t write to this file.
ForWriting 2 Open a file for writing.
ForAppending 8 Open a file and write to the end of the file.

Notice it has a ForAppending attribute? If you wanted to … say log a series of collected values over a number of calls to the script you would have to change the access method to appending, however, keep in mind that ForAppending assumes the file already exists and you will receive an error if it doesn’t.

So, here is the script to write a file…

Option Explicit
Dim Error

Error = WriteTextFile (“c:\test.txt”, “I created a text file with VBScript!”)
If Error = 0 Then
    WScript.Echo “File Written Correctly.”
    WScript.Echo”Error number ” & Error & ” occurred.”
End If

Function WriteTextFile (OutputFile, Data)
    Dim wrtlog, fso
    ‘these are constants for the OpenTextFile method’s file access modes
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    On Error Resume Next
    Set fso = CreateObject(“Scripting.FileSystemObject”)
    Set wrtlog = fso.OpenTextFile (OutputFile, ForWriting , true)

    WriteTextFile = Err.Number ‘You can use Err.Description here to debug.
End Function

That’s it. Small, but a VERY powerful tool to add to your tool belt in scripting.

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 ( File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!

Extra credit: Can you modify this function to accept a third parameter for the access method? I invite you to leave a comment and I’ll let you know if your on the same track as I am. Comments are always welcome!

April 16, 2008  7:11 PM

VBScript to check CPU and Processor performance counter statistics using WMI

Jerry Lees Jerry Lees Profile: Jerry Lees

By now, if your reading my blog you’ve had a chance to play with the script I posted for Using VBScript to gather server performance counter data with WMI . But I think I might know what you’re thinking– “Hey, that’s cool… but I could careless about knowing how much non-paged pool memory there is being used on the system! I need to track something useful, like processor utilization or  something else!

Well, you can– and here you go!  As always the code itself is available on my website in the File Depot if you’d like to avoid copy/paste problems or you don’t want to type the code yourself.

This script has two functions in it, GetFormattedCPU() and GetRAWCPU() which both do the same thing, except that one uses a raw performance counter (Win32_PerfRawData_PerfOS_Processor) and the other uses a preformatted counter (Win32_PerfFormattedData_PerfOS_Processor) to get the information from the system. These two counter types, as you will see, give you very different numbers and for the most part you should probably stick with the preformatted counters if at all possible so you don’t have to do a ton of math to get meaningful data.

The functions both return a Comma Delimited string that contains the CPU percentage usage for all processors in the system. Note that, on my dual core system I get 3 numbers– respective to the return value; Processor 0, Processor 1, and _Total. This should work equally well on Physical SMP systems that are either single or Dual Core, but I suspect on a single core system with more than two processors you will get two numbers that are identical… unfortunately, I no longer have a single core system I can test on.

As always, the code is written in such a way that you can replace the “.” with a “server name” and it will work remotely on a system– providing you have administrative rights. Here is the code:

Option Explicit
On Error Goto 0
Dim strSrv, strQuery

strSrv = “.”

WScript.Echo GetFormattedCPU(StrSrv)
WScript.Echo GetRAWCPU(StrSrv)

Function GetFormattedCPU(strSrv)
    Dim objWMIService, Item, Proc
    strQuery = “select * from Win32_PerfFormattedData_PerfOS_Processor”
    Set objWMIService = GetObject(“winmgmts:\\” & StrSrv & “\root\cimv2”)
Set Item = objWMIService.ExecQuery(strQuery,,48)
    WScript.Echo strQuery
    For Each Proc In Item
       GetFormattedCPU = GetFormattedCPU & Proc.PercentProcessorTime & “, ”
       wscript.echo “Processor ” & Proc.Name & ” = ” & Proc.PercentProcessorTime
End Function

Function GetRAWCPU(StrSrv)
      Dim objWMIService, Item, Proc
      strQuery = “select * from Win32_PerfRawData_PerfOS_Processor”
      Set objWMIService = GetObject(“winmgmts:\\” & StrSrv & “\root\cimv2”)
      Set Item = objWMIService.ExecQuery(strQuery,,48)
     WScript.Echo strQuery
     For Each Proc In Item
         GetRAWCPU= GetRAWCPU & Proc.PercentProcessorTime & “,”
         wscript.echo “Processor ” & Proc.Name & ” = ” & Proc.PercentProcessorTime
End Function

That’s it!! As a point of reference, the output of this script looks as follows: 

select * from Win32_PerfFormattedData_PerfOS_Processor
Processor 0 = 0
Processor 1 = 0
Processor _Total = 0
0, 0, 0,
select * from Win32_PerfRawData_PerfOS_Processor
Processor 0 = 273670781250
Processor 1 = 275960625000
Processor _Total = 274815703125

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 ( File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!

Extra credit: Can you guess why I would have messed up your output from the functions in this script by separating the numbers with commas? I invite you to leave a comment and I’ll let you know if your on the same track as I am. Comments are always welcome!

April 13, 2008  1:40 AM

Converting variable types in vbscript from one type to another type

Jerry Lees Jerry Lees Profile: Jerry Lees

In a previous posting, titled Variable types in VBscript and their upper and lower limits— just prior to my Rant about CAPTCHA, we discussed the types of variables and why you might want to use them and I showed you a few scenarios where you could get unpredicatable results by not using the proper variable type. If you haven’t had a chance to read it yet, you might want to go back here before continuing.

In this installment We’ll discuss the challenge created by using these variable types specifically. Remember, I said that if you use pieces of code or a COM object written in another language it may require a certain type of variable when you call it from your script. (Note, VBScript generally does a good job of converting for you behind the scenes, but it is a best practice to do the conversion on your own first.)  You might be thinking, “Why not just use a double for everything, that covers a wide enough amount of numbers that I’ll never be able to use a number that high?”

Well, the reason is the size of the amount of data it takes because a larger number takes more bits in binary to be represented– therefor the larger the number (or more correctly the RANGE of the variable type) the more space it will take to store it. (A binary lesson may be in order, but not today.)  The last reason is related to the size as well, it takes more processing power to deal with larger numbers because the bus of the CPU is only so wide, and it must sometimes bring the number across the bus in two steps, thus taking more time. Therefore, if you use numbers to big your  scripts can run slower. When I mean slower, I’m only talking about fractions of a second for the work to be complete, but slow scripts tend to each your life away a millisecond at a time… Imagine something being a millisecond slower but you have to do it 100,000 times. Now you’re looking at almost 2 minutes eaten away.

Now, We discussed the types of variables last time, below you will find a table that shows you the function that converts one variable type to another and a link to a useful site showing you how to use the function. Yes, a function. These get fed a number of one type and return a number of another, so you’ll need to assign the return to another variable when you call them.  (Note: the site referenced uses document.write in it’s examples, to use the examples in VBScript simply replace document.write with a wscript.echo)

VBScript Type Conversion Functions

Function Description
CBool Converts any nonzero value to True and 0 (zero) to False.
CByte Converts an expression to a Byte value.
CCur Converts an expression to a Currency value.
CDate Converts an expression to a Date value.
CDbl Converts an expression to a Double value.
CInt Converts an expression to an Integer value. If the fractional part of the expression is .5, CInt will round the value to the nearest even number. For example, 3.5 will be rounded to 4, and 6.5 will be rounded to 6.
CLng Converts an expression to a Long value.
CSng Converts an expression to a Single value.
CStr Converts an expression to a String value.

This information should be very helpful to you in coverting variables from one type to another in the future. The thing to remember is that you don’t always need to do this, but if you’re getting wierd results in your script; check for uninitialized variants, variables of one type (or variant) that are being used with a external piece of code from another language, or for places where a return value is one type and you use it as another.


Extra credit: What happens if you have a variable (of any type) and add enough to it to cause it to go above the maximum value of the variable type? What’s this generally called?

April 7, 2008  5:19 PM

Rant: Anyone else dislike those “enter the letters you see below” confirmation pages?

Jerry Lees Jerry Lees Profile: Jerry Lees

Ok, you guys know I try to at least stay on topic with respect to systems administration… but this time, as a systems administrator, I have to just share my complete frustration with a technology in use these days entirely to much, in my opinion.

That technology is the use of the automated images that are shown on pages that you have to enter the text shown in the image. I can never get them right the first time, but this one takes the cake!

 This has simply got to be the WORST one I have ever seen! I mean, I see gsp there– but what are those other letters? tun? tia? tian?tim? lun? I gave up.

Most sites do this so that scripters will not be able to write scripts that automatically post comments to discussion boards, like spam e-mails, with no real person actually doing the posting. It’s supposed to “verify your humanity”– however, you’ll have to take my word for it– I am human! If your reading this and you own a  site that does this to us or are considering it– please find a better way to protect us from the spam bots!

 Some other ways they do this is with multi colored text. And while I’m not color blind, they generally do it with reds, greens, and blues– three colors that are hard to see if you are color blind.

All this trouble simply because some yahoo thinks he’s going to get rich by posting comments and sending e-mails about prescription drugs, a stock tip, or some other stuff. (We’ve all seen them, so I don’t have to go into detail here. Thankfully.)

At any rate, thank you for listening… back to your regularly scheduled systems administration duties. If get a chance post a comment with your favorite experiences with this frustration, I’m sure we’d all love to read them!

April 6, 2008  12:17 AM

Variable types in VBscript and their upper and lower limits

Jerry Lees Jerry Lees Profile: Jerry Lees

I just realized that the direction I’m headed with this blog (atleast a few posts from now) requires that I give you some more background information beyond what I’ve already done.

 Previously, I’ve talked about variables and given you a few types in passing– but never detailed the different types that are available to you as a script writer.

To that I say, “VBscripts default variable type is a Variant, which can hold any type of value you need to put in it without any work at all on your part.”

“WAIT?!?!!”, you say, “Here you are harping on us to be lazy and now you’re about to go through a big posting on variable types when the one you just mentioned should work fine for me!??”

Yes, a variant will work just fine for you for the most part. But it does do some funny things with variables because under the hood it does the conversion for you. Some even say using variants slows things down. Sometimes in VBscript you need to interface with an external COM dll or some other program and the other variable types will be needed because the call to the DLL will break if your variables aren’t properly cast into a type. Also, variants do funny things to numbers… take this simple example.

x = 2.0000
WScript.Echo x

 When you run this it simply prints:


No, No, No! I set x to 2.000 not 2. You might be thinking that 2.000 = 2 from your math days and you’d be right except some of your science folks out there will agree that sometimes you need to communicate precision as well. In science, 2.000 communicates that you’ve MEASURED something to the thousandth place to be exactly 2.000. Frankly, that can sometimes take work and if you’re lazy and you do all that work you want credit for it, right? (See how I brought that ramble back full circle? Be lazy!)

Also, It does some funky things with variables you’ve never set to a value as well. Since Variants are just that– you can use them for strings, like for a URL “” and numbers like 100. No problem, right? Again… Possibly it’s a problem… Consider this scenario in your script (with nothing else in the script): 

WScript.Echo y
WScript.Echo y + 1

This prints the following (between the _ characters below on two different lines to show you what happens):



See it? The first echo of y appears blank– yet when I add it to the number 1, I get 1!  That’s because if you don’t put a value in a variant variable it treats it is 0 if it is used in the context of a number and as an empty string (or NULL (Not “”, or the empty string) for you C/C++ programmers out there) if you use it in the context of a string. Big difference huh? Same Y, but two different values– empty and 0! (On a side note, think about empty with respect to a file’s contents– Empty takes no space at all and 0 (zero) takes a whole byte in a file.)

Now that you see some slight differences, consider the following types of variables in the table below: 

Subtype Description
Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-length string (“”) for string variables.
Null Variant intentionally contains no valid data.
Boolean Contains either True or False.
Byte Contains integer in the range 0 to 255.
Integer Contains integer in the range -32,768 to 32,767.
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long Contains integer in the range -2,147,483,648 to 2,147,483,647.
Single Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Date (Time) Contains a number that represents a date between January 1, 100 to December 31, 9999.
String Contains a variable-length string that can be up to approximately 2 billion characters in length.
Object Contains an object.
Error Contains an error number.

All these number types… I’m betting your head is swimming if you haven’t encountered this before. Have no fear… we’ll go over them more a little later. Atleast, for now you see what I’m talking about. Next time, I’ll go over conversion functions to convert number types.

Extra Credit: Think about if I had a payroll script I was working on– and you were actually going to get paid by it. You worked 40.5 hours (or if your salary your check should be $1201.62) Would you mind terribly if I fed this to the payroll department after converting these numbers to an Integer first?

April 2, 2008  2:49 PM

Using Vbscript to gather server performance counter data with WMI

Jerry Lees Jerry Lees Profile: Jerry Lees

In my last entry I shared with you how to use WMI in Vbscript to reboot a server from a scheduled job (either locally or remotely) and I hinted at a scenario where I needed to use this script because a server had a memory leak in an application (Trend Micro OfficeScan 8.0, to be exact). They’ve got a fix out but we just upgraded to 8.0 and apparently that didn’t go well, plus this patch is a server patch that immediately rolls out to the clients– so they are less than willing to jump onto the razor’s edge with a patch. (Politics– We’ve all been there, right?)

 Well, in this entry I’m going to share the function I wrote to pull Poolmemory Non-Paged Bytes from the server using Win32_PerfFormattedData_PerfOS_Memory. I’ll not go into detail about this class and its functions and members here in this posting, but you can find out more details at Microsoft’s MSDN site here. Remember from a previous post (Determining properties and methods used in a WMI object for use in a vbscript), that you can always find out what properties are available by looking at the class definition of these pages.

 The function I wrote pulls the PoolnonpagedBytes property from the Win32_PerfFormattedData_PerfOS_Memory object. This function requires you to pass it the last value of the performance counter. While it doesn’t use it to get the data it does internal to the function compute the delta of the last and the new value– which is handy if your logging and/or monitoring in real time troubleshooting.

The following is a function only, not a complete vbscript to save space and to focus in on this part of the code. For a complete working example script that is tehone I’ve been talking about in the last two posts go here that combines the previous posting’s reboot function, this function, and takes into account the number of times a value can exceed a threshhold during a time frame look here in the vbscript section for “non-paged pool memory“.

Function GetMem(last)
     Set oLoc=CreateObject(“WbemScripting.SWbemLocator”)
     Set owmi=oLoc.ConnectServer(strSrv,”root\cimv2″)
     Set oRef=oWmi.ExecQuery(strQuery)

     For Each detail In oRef
         Newval = detail.PoolNonpagedBytes
         WScript.Echo Newval & vbtab & Newval-last
         getmem = (Newval/1024)/1024
End Function

Obviously, you have to do some work before you call the function setting up both a variable to recieve the return and also some sort of variable to keep track of the last value. If you aren’t after tracking the changes and only want the return value you can pass any number, including zero, to the fuction and remove the wscript.echo lines in the above code snippet.

Also, since it’s a snippet and as I write this I noticed that you will need some setup in the main routine like:

  •  a variable in your main script called strSrv that has the name of the server you want to pull the value of the counter.
  •  The following line in the main routine that sets up the “SQL” call for WMI and initializes the value of strQuery. (Btw, for a good back to basics look at SQL calls, check out the SQL Server with Mr. Denny Blog here on ITKE.)

              strQuery=”SELECT * From Win32_PerfFormattedData_PerfOS_Memory”

You can find more performance monitor classes that are available to you here. Basically, if it’s available in perfmon– you can get it with vbscript! Just look for classes named like Win32_PerfFormattedData…. or Win32_PerfRawData…, these classes will get you what you want. Keep in mind that Raw data is just that and most times you are going to want to get PrefFormatted data in the beginning. If you’d like more information on the differences, post a comment and I’ll come back to it later.

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 ( File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!

Extra credit: This is double extra credit, I guess, in my last entry I gave you a hint at my last extra credit question in my previous post– I just made the call a different way. The last posting asked you about what this part of the code did:


Does this help give you more information to go on?

March 27, 2008  3:03 PM

Rebooting or Shuttingdown a Server Remotely with VBScript

Jerry Lees Jerry Lees Profile: Jerry Lees

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.)


Function Reboot(StrSrv)
   Set objWMIService = GetObject(_
& StrSrv & “\root\cimv2”)
   Set colItems = objWMIService.ExecQuery(“Select * from Win32_OperatingSystem”,,48)
   For Each objItem In colItems
        WScript.Echo objitem.Reboot
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 ( 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)}

March 24, 2008  3:03 PM

Found discount: 50% off Kaspersky Antivirus Products

Jerry Lees Jerry Lees Profile: Jerry Lees

I don’t normally think enough about a product to pass these things on, or the discount isn’t real enough to warrant my bugging you with the information– but I recently found a link to Kaspersky Anti-Virus Products where they are offering almost 50% off your entire purchase of their antivirus products.

Thier products are pretty good, offering both home and business Antivirus solutions, and they are inexpensive enough to warrant a look if your in the market for antivirus software.

As I understand it, the offer is until March 31st and you enter the code 50KMS into the cart on checkout and the cost of the order is cut in about half. That’s substantial. When I tried it, the code wasn’t needed it looked like it was already discounted through the link I found above when I compared the shown prices with the website’s prices.

 Essentially, it ended up being $39.95 for a year of their latest antivirus application and only $20 for their newest mobil security product for smartphones and PDAs.

If your in the market for antivirus software– or looking to upgrade your current version of their product you might check it out.

Recently Updated:

Since the links above have expired, below is a link that is current for discounts to Kaspersky antivirus products:

Receive a discount on Kaspersky Lab products

March 21, 2008  5:39 PM

Explanation: Using Microsoft.XMLDOM to work with data feeds in VBScript

Jerry Lees Jerry Lees Profile: Jerry Lees

You may recall we recently worked with a cool little script that itself didn’t have anything to do with systems administration, the 360voice API script in a previous post, but the concepts can be used in many different areas since XML data feeds are ever becoming the standard way to communicate related data between applications and systems.

In this script, I used many topics we’ve previously discussed and added a powerful object, Microsoft.XMLDOM. Essentially, DOM stands for Document Object Model– which is a way for the document to describe and relate the data it contains. Here is an example XML document header for “mydata”

<?xml version=”1.0″?>
<!DOCTYPE Mydata SYSTEM “mydata.dtd”>

This essentially in the first line tells us the file is an XML document, Version 1.0 to be specific, and in the second line tells us the Document Type Definition file that we can have the parser verify the XML file against. DTD’s and XML Schemas are beyond the scope of what we’re discussing but can be very useful becasue they define the rules by which a XML document must conform to be considered valid– however they are not required to be in an XML file.

After these lines the XML file has nodes and child nodes in it. This is where the bulk of our work was done going through the nodes and pulling out child nodes and values. In this illustration we’ll use the following URL to my XML Game data at (note the data will change over time, but the datastructure should stay pretty much the same)

As of this moment, the file looks like:

<?xml version=”1.0″ encoding=”ISO-8859-1″ ?>

<date>3/20/2008 4:42:02 AM</date>
<date>3/19/2008 4:45:18 AM</date>

Notice how the main Node (The “document” Node) is titled api? The XML Parser automatically read that entire node in at the load of the document. After that we have nodes called info and gamerscore that both contain data and/or child nodes.

the info tag contains the version and gamertag values, you’ll notice I used the gamertag value in the script to pull the name of the gamertag with this line of the script code after checking to see if the currently looped through tag had the name “info”:

WScript.Echo GetTagValue(x,”gamertag”)

See how that works? This example was pretty simple since it was just off the root. The score value and date were a bit harder to get at, but not to bad.

They are contained in a child node called “score”, but they are a child of gamerscore– so you’ll see that I check to see if the tag is “gamerscore” and then loop through the score tag separately looking for each instance of the node called score and pulling the tag value and placing it into an array called gamerscore.

All pretty straightforward. There are certainly better ways to deal with XML than writing code tightly around the XML itself, but this illustrates the use of Microsoft.XMLDOM and explains the heirarchial nature of XML nicely the way it’s been coded.

See if you can play around with the code and make it better! Thanks again to the folks at 360voice for providing the API and it’s documentation!

Happy coding and have fun!

March 20, 2008  6:26 PM

Explanation: Working with Subroutines and Functions in VBScript

Jerry Lees Jerry Lees Profile: Jerry Lees

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
MySub 10
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)
X = MyFunction (10)
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!

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: