May 9 2008 5:54PM GMT
Posted by: Jerry Lees
vbscriptstatements,
VBScript Statements,
VBScript,
Functions
The Select … Case Vbscript statement is a very powerful way to easily preform specific actions based on a comparison of a variable to a series of cases you specify, plus it allows for the fact that NONE of the cases apply with an optional case else condition. The Select Case statement is often a better solution then a if…Then…Else if when you have more than 2 conditions that could apply.
Consider the following code snippet to check if a number is positive or negative:
Function TestNumber(Number)
Select case Number
Case Number > 0
TestNumber = “Positive”
Case Number < 0
TestNumber = “Negative”
Case Else
TestNumber = “Zero”
End Select
May 9 2008 4:28PM GMT
Posted by: Jerry Lees
Excel.Application,
VBScript
In my previous two postings we discussed the Microsoft Word.Application object (here and here) to use as a logging mechanism and as a documentation mechanism for our scripts we’re writing.
But what about if you wanted to log numbers, like in the performance counter posts I made a few weeks back? I’ve also seen several questions about how to do use excel in vbscript. Well, it’s super easy, once you get the object understood. The next few postings I’ll focus on this great way to save data in a format that is easily shareable and can easily be made into pretty pie charts and such for the boss.
First off I’ll give you a simple example that basically creates the object (not visible), adds a new workbook to it, adds a string to cell 1,1, and finally saves it before it quits. Below is the example code for this scriptlet:
Const xlSaveChanges = 1
Set objExcel = CreateObject(”Excel.Application”)
objExcel.Visible = False
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = “Test value”
objExcel.ActiveWorkbook.SaveAs (”C:\excelvbscript.xls”)
objExcel.Quit
I’ll dig deeper right after I go back and explain the Select Case statement I used in a previous posting– which I neglected to mention previously or explain in the posting. (Bad, Jerry, Bad Bad.) Hwever, after that I promis to come back with a more specific example of Excel.Application, but this should give you a little bit to play with in the mean time.
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 XML files and Generated Word Documents for you. You’ll find the code available for download from my website’s (www.webstemsadministration.com) File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!
May 2 2008 4:15PM GMT
Posted by: Jerry Lees
Functions,
DataManagement,
Microsoft.XMLDOM,
VBA,
VBScript,
XML,
Word.application,
Documentation
OK, here is the posting I hinted at in my previous posting this week entitiled, Using Vbscript to create Word documents automatically with the Word.Application Object. In that posting I mentioned a project where I had to create a ton of documentation… but I didn’t say what it was that I had to document. Yeap, you guessed it from this article’s title… Group Policy Settings! I had to document settings in a series of policies I was proposing we implement at my employer. Here is the scenario:
I was asked “Can you document all the settings you are proposing in the new policies for the other members of IT? Also, Can you document the name of the setting, what you want it to be and what options are available to change it to? Oh, and what each value means when you set it?…. Do you think you’ll have time to also let us know for each setting what the supported or intended OS version is for the setting? I need it by Friday.”
Now, much like you might do, I said “I’ll try.” and mumbled under my breath later “If you bring me a pound of Lead I’ll turn it to Gold too!”… None the less, after my initial pitty party, I began looking at the Information available to me in the Group Policy Management Console (Available here if you don’t have it already.), much to my surprise I found almost everything I needed when I looked at the individual settings… it just wasn’t in a format I could show to people or they could read easily. So I set out to try and copy and paste the information into word… for 20 seconds… and realized this is way to much work! And what do I always say?????? Be Lazy!
Now I looked at the options available to me on exporting the file and CSV was one of them, but unfortunately all the relationships were lost and I couldn’t make heads or tails of how to cobble it back together in a meaningful way after the export. Then I noticed XML and remembered my last post on Microsoft.XMLDOM (Using XML in vbscript via Microsoft.XMLDOM to work with data feeds) and thought, I really need to get back to that… so here we are!
First, Just like my last post– you’ll need Microsoft Word installed where you run this script for it to operate. Then you’ll need to use The Group Policy Management console to export the policy settings to XML. (hover over the icons along the top, it’s the one with the icon that looks like a page of paper with an arrow pointing right, one of the save as options is XML.) Save this file into the location where the script is located (I recommend a descriptive name, because it will be the heading for your document.) and with a single edit of the script you will have a word doc on the root of your C: drive with the same name— only documented in Word!
The script basically opens and reads in the XML Document and creates a Word.Application object to create a Microsoft Word Document at the root of the C: Drive, then writes formatted text to the document to make the data in the XML readable. But, enough of a introduction! On to the script! Here is the script:
set xmlDoc=CreateObject(”Microsoft.XMLDOM”)
Set objWord = CreateObject(”Word.Application”)
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection
‘This is the actual name of the XML document minus the path and the “.XML” extension, it becomes the word doc header
xmlfile = “Locked Down Desktop Policy”
objSelection.Font.Name = “Arial”
objSelection.Font.Size = “18″
objSelection.Font.Bold = True
objSelection.TypeText xmlfile & VbCrLf
objSelection.Font.Bold = False
objSelection.Font.Size = “10″
xmlDoc.async=”false”
xmlDoc.load(xmlfile &”.xml”)
for each x in xmlDoc.documentElement.childNodes
If x.nodename = “Computer” or x.nodename = “User” Then
For Each y In x.childnodes
if y.Nodename = “ExtensionData” then
For Each z In y.childnodes
If z.Nodename = “Extension” Then
For Each setting In z.childnodes
objSelection.TypeText “______________________________________” & vbCr
DocumentPolicy(Setting)
Next
End if
Next
End if
Next
End If
Next
objDoc.SaveAs(”C:\” & xmlfile & “.doc”)
objWord.Quit
Function DocumentPolicy(Setting)
‘this function basically cleans up the headers of the word document, so they are more human readable
Select Case setting.nodename
Case “q1:Policy”
replacestr = “q1:”
Case “q1:DropDownList”
replacestr = “q1:”
Case “q1:Name”
replacestr = “q1:”
Case “q1:Value”
replacestr = “q1:”
Case “q1:State”
replacestr = “q1:”
Case “q2:Audit”
replacestr = “q2:”
Case “q2:SecurityOptions”
replacestr = “q2:”
Case “q2:EventLog”
replacestr = “q2:”
Case “q2:RestrictedGroups”
replacestr = “q2:”
Case “q2:File”
replacestr = “q2:”
Case “q2:Display”
replacestr = “q2:”
Case “q3:General”
replacestr = “q3:”
Case “q3:HashRule”
replacestr = “q3:”
Case “q3:PathRule”
replacestr = “q3:”
Case “q3:InternetZoneRule”
replacestr = “q3:”
Case “q4:AutoEnrollmentSettings”
replacestr = “q4:”
Case “q4:AutoEnrollmentSettings”
replacestr = “q4:”
Case “q4:RootCertificateSettings”
replacestr = “q4:”
Case “q4:EFSSettings”
replacestr = “q4:”
Case “q5:PreferenceMode”
replacestr = “q5:”
Case “q2:PreferenceMode”
replacestr = “q2:”
Case “q2:ProxySettings”
replacestr = “q2:”
Case “q2:UseSameProxy:”
replacestr = “q2:”
Case “q2:HTTP:”
replacestr = “q2:”
Case “q2:NoProxyIntranet:”
replacestr = “q2:”End Select
objSelection.Font.Bold = True
objSelection.TypeText VbCrLf & replace(setting.nodename, replacestr,”") & VbCrLf
objSelection.Font.Bold = False
For Each Value In Setting.Childnodes
NodeName = replace(Value.nodename,replacestr,”")
If NodeName = “Explain” Then
objSelection.Font.Bold = True
objSelection.TypeText Nodename & “: ” & vbcrlf
objSelection.Font.Bold = False
objSelection.TypeText vbTab & replace(value.text,”\n\n”, VbCrLf & VbCrLf & vbTab )& vbcrlf
Else
objSelection.Font.Bold = True
objSelection.TypeText Nodename & “: “
objSelection.Font.Bold = False
objSelection.TypeText vbtab & value.text & vbcrlf
End if
Next
If isnull(Setting.childnodes) Then
For Each node In Setting.childnodes
DocumentPolicy(node)
next
End if
objSelection.TypeText VbCrLf
End Function
Now, when you run this script agains your export there may be some XML tags I didn’t notice because a setting you set is one I didn’t set. Any time you see them in the document you can add a new Case statement in the select case followed by setting the replacestr to the string you want to replace with a null. The lines I’m talking about look similar to this:
Case “q2:xxxxxxxx”
replacestr = “q2:”
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 XML files and Generated Word Documents for you. You’ll find the code available for download from my website’s (www.webstemsadministration.com) File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!
Apr 30 2008 2:20PM GMT
Posted by: Jerry Lees
Word.application,
VBA,
DataManagement,
VBScript,
Developer documentation,
Documentation
I recently had a project that required me to create a ton of documentation from data that was already stored in files elsewhere on the network– just not in the format that was required and readable by every day people within IT. (Basically, non-administrators) This project would have required a TON of copy and paste operations or a whole lot MORE reworking of a document, plus I was on a tight deadline. So I decided to use a little VBA (Visual Basic for Applications) knowledge I had picked up in the past to work with the Microsoft Word Application interface and do the job, with only minor reworking after the fact to really tiddy up the document.
First, let me clarify. Most of my scripts I use here require nothing more than the items I mentioned in my first posting (Getting Started Writing VBScript to Administer a Windows 2000 or 2003 Network) on this blog… a Vbscript editor. (Notepad will do… but you’ll likely quickly want something a bit more powerful before long.) The scripts I discuss in this series are one exception, for these scripts we discuss in the next few articles we will need to make sure you have Microsoft Word installed where ever you run the script. However, for the purposes of this type of work your workstation should work fine and will likely already have Microsoft word installed! Bonus!
The “magic” component we need to call and create an object from is called Word.application, as you’ll see below, it’s pretty easy to create a word document from vbscript and then have autogenerating documentation!
The next sections of code will show you how to do various tasks with in word. Many sections are not scripts on themselves, but infact snippets that could be placed into the first script prior to the remark for testing. The first snippet, creates a word document and saves it to the root of your C: drive. When you run this it will run, but create a blank word document– much like if you right clicked somewhere and selected New/Microsoftw Word Document. Here are some common tasks in word I use:
Create a new (empty) Word Document and save it to c:\testdoc.doc
Set objWord = CreateObject(”Word.Application”)
‘note: if you don’t want word popping up and displaying as this is built– set this next line to False
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
’save the Word Document
objDoc.SaveAs(”C:\testdoc.doc”)
Setting the Font type
objSelection.Font.Name = “Arial”
Setting the Font Size
objSelection.Font.Size = “18″
Adding Text
objSelection.TypeText “Add your text here”
objSelection.TypeParagraph()
Setting the typeface to bold
objSelection.Font.Bold = True
Closing the word document (generally done after saving)
objWord.Quit
These should get you started playing with Vbscript to create word documents. For more information on working with microsoft word in vbscript look here at Microsoft’s site, while it’s not related exactly to vbscript– it should give you enough information about the interface to get started.
Next time, I’ll share a script to document settings in Group policy with a word document through a combination of using Word.Application and Microsoft.XMLDOM.
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 for you. From here on out I will make the code available for download from my website’s (www.webstemsadministration.com) File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!
Apr 25 2008 3:19PM GMT
Posted by: Jerry Lees
Variable Types,
VBScript
In a previous posting, Converting variable types in vbscript from one type to another type, I discussed very briefly binary numbers and promised to write another entry with more detail. If you recall we we were discussing the size a number takes up to represent it in binary form.
Everyone is comfortable with the numbers 1 and 0, even in binary. And if you’re in IT, you’re probably even comfortable with binary 10, which isn’t Ten– it’s two. Normally we count in tens (with ten digits in each place), but computers count in twos (with only two digits in each place), which is base-2 instead of base-10 like we are used to counting.
Consider this base-10 table with the colun lables at the top and the number of each column below.
|
10000
|
1000
|
100
|
10
|
0
|
|
9
|
8
|
1
|
5
|
3
|
This might look a bit abstract the way it’s presented. But if you think back to elementary school the columns in a number represent the 10’s, 100’s, etc for the number. But the number is 98,153 or (90,000 +8000+ 100+50+3)
Now consider the following binary number, again with the column label at the top and the number of each column at the bottom:
This looks a bit more cryptic, but it’s actually simpler– we’ve just been trained to think in decimal. To do the first one we actually had to do multiplication in our head. It wasn’t (90,000 +8000+ 100+50+3)— it was actually(9* 10,000) + (8* 1000) + (1 * 100) + (5 * 10) + (3* 1)… That’s rather confusing when you spread it out, isn’t it? but with only 1’s and 0’s we don’t need to do multiplication. (Because 1 * anything is the number, and 0 times anything is 0)
So this is simply 16+4+2+1, or 23! It’s just a matter of getting to start thinking in powers of 2!
Now, Since I’ve shared with you previously that a double is larger than an integer, with respect to space, we’ll continue with that example. If you refer here you’ll notice that an integer is 2 bytes in Size where a double is 8 bytes in size. What’s 400% more space amoung friends, right? Quickly doubles can get out of control is you’re using bunches of them, or placing them in a Database one item at a time… This is sometimes where developers eat up all our space on the servers, in addition to the backup of the backups in the backups folder that’s stored in a Do not delete - Save this stuff folder.
The other thing that can be VERY bad! is using a variable type that is to small. Did you notice in the previous link that in Integer represents -32,768 to 32,768? What happens if you add 1 to 32,768? The answer for us is, of course, 32,769! The problem is computers can’t represent that number in an integer so you get a overflow and the number represented actually looks like -32768 to the computer!
The moral of the story is to always try to use the right type of variable if a variant doesn’t work for you, and if you plan on using anything other than vbscript, VB, VB.NET, or VBA to create an admin tool– get accustomed to the different variable types.
Enjoy!
Extra credit: 10 in base-10 numbering is Ten, 10 in base-2 numbering is 2… what is 10 in Base-16 numbering and what is it commonly called?
Apr 25 2008 1:26AM GMT
Posted by: Jerry Lees
Error control,
File System Object,
Functions,
VBScript,
Scripting.FileSystemObject
Last time, in my entry entitled Vbscript to check CPU and Processor performance counter statistics using WMI, I asked you to modify the code I gave to include the access method type in the function. If you haven’t read teh article, take a second to go back and look it over and digest the code because this article is identicle to that one, except some added features.
Again I got a rather quick response to the extra credit item that I placed at the end if the article. Basically, you just need to change the code in three places to accomplish this task. We could then use this code in our previous example to create a CSV file for trending and graphing of CPU usage on a server! Here is an example of the code to do this task.
I encourage you to play around with the various methods of file access both with an existing file and a new file that doesn’t exist.
Below is a working example of the code:
Option Explicit
On Error Goto 0
Dim strSrv, strQuery,Errors
Dim Counter, Timeframe, Delay
Delay = 1000 ‘1000 Milliseconds to a second
Timeframe = 300 ’seconds (5 minutes)
strSrv = “.”
For Counter = 1 To Timeframe
Errors = WriteTextFile (”c:\cpu-usagelog.csv”, GetFormattedCPU (strSrv), ForAppending)
WScript.Sleep Delay
NextConst ForReading = 1, ForWriting = 2, ForAppending = 8Function GetFormattedCPU(strSrv)
Dim objWMIService, Item, Proc, start
start = Now()
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
Next
GetFormattedCPU = GetFormattedCPU & start
End FunctionFunction WriteTextFile (OutputFile, Data, AccessType)
Dim wrtlog, fso
On Error Resume Next
Set fso = CreateObject(”Scripting.FileSystemObject”)
Set wrtlog = fso.OpenTextFile (OutputFile, AccessType, true)
If Err.Number <> 0 Then
Set wrtlog = fso.OpenTextFile (OutputFile, ForWriting, true)
End If
wrtlog.WriteLine(Data)
WriteTextFile = Err.Number ‘You can use Err.Description here to debug.
On Error Goto 0
End FunctionYou now have all the pieces for a fully functional performance logging script, so you’re well on your way to being able to trobleshoot problems deep in the night without getting up and turning on perfmon. The creates a comma separated value file called cpu-usagelog.csv at the root of the C: drive while the output looks similar to the last time, except it is repeated and I put a time/date stamp in the code by using a new command, now().Also, pay attention to the error handling around the line that writes the data to the file, you’ll likely not see an error related to thefile not existing and you using the append access methods, becasue i’ve checked for it while opening a file. Lastly, notice the for next loop around the function call to call it Timeframe times (Timeframe is multiplied time the sleep Delay to get how long it will capture data). Also notice another new command:
Wscript.sleep, which basically pauses the execution for the number of milliseconds you specify in Delay.
Again, 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 for you. From here on out I will make the code available for download from my website’s (www.webstemsadministration.com) File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!
Extra credit: Try and modify this script to monitor something else that is useful to you. Let us all know how you’ve used it.
Apr 17 2008 8:52PM GMT
Posted by: Jerry Lees
FSO,
File System Object,
Scripting.FileSystemObject,
VBScript,
log files,
Functions
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 textfile” 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 filename 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 easliy 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 assunmes the file already exists and you will recieve 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.”
Else
WScript.Echo”Error number ” & Error & ” occured.”
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)
wrtlog.WriteLine(Data)
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 toolbelt in scripting.
Again, 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 for you. From here on out I will make the code available for download from my website’s (www.webstemsadministration.com) 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!
Apr 16 2008 7:11PM GMT
Posted by: Jerry Lees
Functions,
DataCenter,
Development,
VBScript,
Remote management,
PerfMon,
Windows Management Interface,
Administration tools
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 pre-formatted 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 teh pre-formatted 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 percantage 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 identicle… 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”______”
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
Next
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
Next
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
273670781250,275960625000,274815703125,
Again, 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 for you. From here on out I will make the code available for download from my website’s (www.webstemsadministration.com) 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!
Apr 13 2008 1:40AM GMT
Posted by: Jerry Lees
Development,
VBScript,
Variable Types,
VBScript Statements,
Functions
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.
Enjoy!
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?