The VBScript Network and Systems Administrator's Cafe:

Scripting.FileSystemObject

May 14 2008   8:58PM GMT

Getting disk usage data with the filesystem object and the Excel.Application object in VBScript



Posted by: Jerry Lees
Documentation, VBScript, FSO, Functions, Scripting.FileSystemObject, File System Object, Excel.Application, system trending, Disk usage

In my previous posting, entitled Working with the Excel.Application object in VBScript to create Excel Spreadsheets, we worked with excel in VBScript to create a excel spreadsheet. The spreadsheet wasn’t going to win any awards for complexity or usefulness, but none the less it was a spreadsheet– and more importantly it was generated by a script! I also promised to bring you a script to help you chart disk space usage in my next posting in the series. This posting is the fulfilment of that promise! Also, please note that you will need Excel installed where the script runs for this script to operate correctly– but it does not need to be installed on the system you are pulling disk free space information from since I used the WMI object instead of the filesystem object.

The script below uses WMI’s Win32_LogicalDisk class to grab the drives in the target system, specifically the drive you specify through the use of a where clause in the SQL statement that pulls back the WMI data. (Through the “where deviceid like” section of the SQL statement in the code)

 Also, I didn’t put a lot of effort into the code where the for/next loop is that loops through getting and saving the free space because I didn’t want to create a lot of extra complexity and wanted to create a script that would run through to completion pretty quickly. Currently, the script takes 10 minutes to complete. To test the script while it’s running, just create files in a folder and delete them a number of times. I created a 10Mb and 20Mb file and made a series of copy/pastes during execution– with a smattering of deletes in the mix.

For further customization, you can look at the code from the posting I wrote a while back Reporting CPU usage by saving it to a file with the VBScript filesystem object to get a good feel for how to modify the loop to get what you want. In essence, change the number 2 in “Wscript.Sleep 2″ to a lager number to get a bigger gap between samples and change the 300 in the “For x = 1 to 300″ line to a larger number to get a longer sample period.

Here is the code:
Dim Freespace, CurrentRow, ServerName
Const xlSaveChanges = 1

‘the first row in excel is 1 (not 0)
CurrentRow = 1
ServerName=”.”

Set objExcel = CreateObject(”Excel.Application”)
objExcel.Visible = False
objExcel.Workbooks.Add
For x = 1 to 300 ‘ change 300 to increase your sample duration
     objExcel.Cells(CurrentRow, 1).Value = GetFreeSpace(”C:”,ServerName)
     CurrentRow = CurrentRow + 1
     Wscript.sleep 2 ‘change this to spread out your samples
next

objExcel.ActiveWorkbook.SaveAs (”C:\excelvbscript.xls”)
objExcel.Quit

Function GetFreeSpace(Drive,strComputer)
     Set objWMIService = GetObject(”winmgmts:{impersonationLevel=impersonate}!\\”_
         & strComputer & “\root\cimv2″)
     Set colDisks = objWMIService.ExecQuery (”Select * from Win32_LogicalDisk where deviceid like “_
         &chr(34) & Drive & chr(34))
     For Each objDisk in colDisks
         GetFreeSpace = (objDisk.freespace/1024)/1024 ‘ get MB free
     Next
End Function

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

Apr 25 2008   1:26AM GMT

Reporting CPU usage by saving it to a file with the VBScript filesystem object



Posted by: Jerry Lees
VBScript, Functions, Error control, Scripting.FileSystemObject, File System Object

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 the article, take a second to go back and look it over and digest the code because this article is identical 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 Function
Function 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 Function
You now have all the pieces for a fully functional performance logging script, so you’re well on your way to being able to troubleshoot 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 the file not existing and you using the append access methods, because 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.

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 (www.websystemsadministration.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

Creating text files using the Scripting.FileSystemObject with VBScript



Posted by: Jerry Lees
VBScript, FSO, Functions, Scripting.FileSystemObject, File System Object, Log files

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

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