Sunday, February 6, 2011

VBScript for QTP Scripting related to File system

Working with File SystemThe main runtime object is the FileSystemObject from which all other runtime objects are derived (except for the dictionary object, which is independent of the FileSystemObject). lists of VBScript runtime objects.
FileSystemObject
ObjectAccess Provided
Drive Disk drive properties
Drives Collection System drive information
File File properties
Files Collection All files contained in the specified folder
Folder Folder properties
Folders Collection All folders contained in the specified folder

To use the FileSystemObject within your VBScripts you must first establish an instance of it. You can do this using the WScript object’s CreateObject() method and by referencing it as Scripting. FileSystemObject. This is demonstrated in the following example.
Set fsoObject = WScript.CreateObject ("Scripting.FileSystemObject")
Here fsoObject is just the name that I assigned to a variable that can now be used by the rest of the script to reference the properties and methods of the FileSystemObject. With this instance of the FileSystemObject now established the script is read to interact with the Windows file system.Let’s put this previous FileSystemObject example to work in a few quick examples to see how it really works.
Displaying Drive Free Space

This first example demonstrates how to use a number of methods and properties of the VBScript runtime objects to access drive information. Specifically the example shown here displays the amount of free space on a computer’s C: and D: drives.
' * Script Name: Script 5.vbs       *  

Option Explicit  

On Error Resume Next  

dim fsoObject, drive1, drive2  

set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")  

set drive1 = fsoObject.GetDrive(fsoObject.GetDriveName("c:"))  

set drive2 = fsoObject.GetDrive(fsoObject.GetDriveName("d:"))  

   

' ********* Main processing section **********  

' Call a function that displays drive information  

Free_Space()  

   

' *********** Procedures go here *************  

' This function displays the amount of free space on drive 1 and drive 2  

   

Function Free_Space()  

 WScript.Echo( "Free Space on drive 1 is: " _  

  & FormatNumber(drive1.FreeSpace / 1024 , 0) & " KB")  

 WScript.Echo( "Free Space on drive 2 is: " _  

  & FormatNumber(drive2.FreeSpace / 1024 , 0) & " KB")  

End Function
The script begins by defining three variables. The first variable is fsoObject. It will be used to create an instance of the FileSystemObject as discussed earlier. The next two variables will be used to set up references to the computer’s C: and D: drives.The two statements that set up the values of these two variables for the computer’s drives probably look a little complex to you at first. So let’s take a moment and break them down. First, the GetDriveName() method of the FileSystemObject is used by appending it to the variable fsoObject (for example, fsoObject.GetDriveName()). Remember that the fsoObject variable provides the script with a reference to the FileSystemObject and its properties and methods. The GetDriveName() method returns the name of the drive associated with the specified driver letter (that is, C: or D:). Next, the FileSystemObject object’s GetDrive() method is used to retrieve the Drive object associated with the specified drive name. The reason that we need to establish a reference to the Drive object is because we are going to want to use its Freespace property a little later in the script. After executing the statements in the script’s initialization section, the VBScript statement in the main processing section executes. There is only one VBScript statement in this section and it calls a function named Display_Msg(). The function then executes. Its job is to display the amount of free space on each drive. This is accomplished by taking the amount of free space left on a given drive as contained by the Drive object’s FreeSpace property and dividing it by 1024 (1 kilobyte or 1 KB). The results are then formatted using the Drive object’s FormatNumber() method, which in this case formats the number with zero trailing decimal spaces (that is, as whole number).When I ran this script on my computer, I got the following results.
C:\>CScript "Script 5.vbs"  

Microsoft (R) Windows Script Host Version 5.6  

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  

Free Space on drive 1 is: 11,116 KB  

Free Space on drive 2 is: 15,784 KB  

C:\>
Examining File System Types
Let’s look at another example of how to work with the methods and properties of the VBScript runtime objects. This time we’ll write a VBScript example that displays the type of file system that the computer’s C: and D: drives have been formatted with.
' * Script Name: Script 6.vbs*  

Option Explicit  

On Error Resume Next  

dim fsoObject, drive1, drive2  

set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")  

set drive1 = fsoObject.GetDrive("C:")  

set drive2 = fsoObject.GetDrive("D:")  

' ********* Main processing section **********  

' Call a function that displays drive information  

Used_Disk()  

' *********** Procedures go here *************  

' This function displays the file system used to format drive 1 and drive 2  

Function Used_Disk()  

 WScript.Echo("The file system used on drive 1 is: " & drive1.FileSystem)  

 WScript.Echo("The file system used on drive 2 is: " & drive2.FileSystem)  

End Function
As you can see this VBScript is similar to the previous example. The same variables are defined in the initialization section. In addition, the same instance of the FileSystemObject is set up and once again its GetDrive() method is used to retrieve Drive object references to each drive on the computer.Next, a single VBScript statement in the main processing section calls a function that displays a file system type for each drive. This is accomplished by using Drive object’s FileSystem property.When I ran this script on my computer I received the following results.
C:\>CScript "Script 6.vbs"  

Microsoft (R) Windows Script Host Version 5.6  

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  

The file system used on drive 1 is: NTFS  

The file system used on drive 2 is: NTFS  

C:\>
Examining File Properties
Let’s look at one final example before we rush off and begin to master the art of reading from and writing to text files. This example starts off like the previous two examples by defining its variables and instantiating an instance of the FileSystemObject. This time the FileSystemObject object’s GetFile() method is used. This method is used to retrieve the File object associated with the specified file, which in this example is c:\winzip.log.Again, a VBScript statement in the main processing section calls on a function named Display_Msg(). The function contains a number of WScript.Echo statements each of which displays a different property associated with the File object.
' ********************************************  

' * Script Name: Script 7.vbs       *  

' * Author: Kuldeep            *  

' * Created: 03/02/08            *  

' ********************************************  

' **** Perform script initialization here ****  

Option Explicit  

On Error Resume Next  

dim fsoObject, targetFile  

set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")  

set targetFile = fsoObject.GetFile("d:\Test.vbs")  

   

' ********* Main processing section **********  

' Call a function that displays drive information  

Details()  

   

' *********** Procedures go here *************  

' This function displays file properties  

Function Details()  

 WScript.Echo("File properties of d:\Test.vbs")  

 WScript.Echo("-----------------------------------")  

 WScript.Echo("Created on:  " & targetFile.DateCreated)  

 WScript.Echo("Last Modified: " & targetFile.DateLastModified)  

 WScript.Echo("Last Accessed: " & targetFile.DateLastAccessed)  

 WScript.Echo("File Name:   " & targetFile.Name)  

 WScript.Echo("File Path:   " & targetFile.Path)  

 WScript.Echo("File Type:   " & targetFile.Type)  

 WScript.Echo("File Size:   " & targetFile.Size)  

End Function
The following output was displayed when I ran this script.
C:\>CScript "Script 7.vbs"  

Microsoft (R) Windows Script Host Version 5.6  

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  

File properties of d:\Test.vbs  

-----------------------------------  

Created on:  2/4/2008 11:23:36 PM  

Last Modified: 2/4/2008 10:38:52 AM  

Last Accessed: 2/4/2008  

File Name:   Test.vbs  

File Path:   D:\Test.vbs  

File Type:   VBScript Script File   

File Size:   1081  

C:\>  
Creating Documents, Reports, and LogsBy this point you should have a fairly good understanding of what the VBScript runtime objects are and what they can do. Now let’s look at how you can use them to generate reports, logs, and other types of text documents.To work with files and their contents you must first establish an instance of the FileSystemObject within your VBScript as shown here.
set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
Next, you should always check to see if the file that you want to work with already exists. If it does, you can open it. If it does not already exist, you can create it and then open it. You can check to see if a file exists using the FileSystemObject object’s FileExists property as shown here.
If (fsoObject.FileExists("C:\displayText.txt" ) ) Then
You must open a file before you can work with it. You can use the FileSystemObject object’s OpenTextFile() method to open files. To use this method you need to supply a few pieces of information including the following. 
·         The name and path of the file to be opened
·         Whether you want the file to be opened for reading, writing, or appending
·         Whether to create the file if it does not existTable defines constants that are used to tell the OpenTextFile() method what you want to do once the file is opened. 

OpenTextFile() Constants
ConstantDescriptionValue
ForReading Opens a file for reading1
ForWriting Opens a file for writing2
ForAppending Opens a file for appending8

Table defines two options that govern what the OpenTextFile() method should do when the file to be opened does and does not exist. 

Table : OpenTextFile() File Creation Options
ValueDescription
True Open the file if it exists, otherwise create and open it
False Open the file if it exists, otherwise do not create it

Opening and Closing Files

It is very important that you correctly specify the type of operation that you are opening a file for (reading, writing, or appending). If you open a file to write to it and the file exists, then the file will be reinitialized. In other words, any data that is already in the file is lost and the file pointer is placed at the beginning of the new file (in the first row and column of the file).By appending to a file, you are able to preserve its contents and add to it. In other words, the file is opened and the file pointer is placed at the end of the file in the last row and column position.The file pointer is used to identify where the next character of data will be placed with a file. In a newly initialized file, the pointer would automatically be positioned in the upper-left corner (row 0, column 0). If one new character of information were added, the pointer would be moved over one position to column 1 in row 0. If a carriage return were added (indicating an end-of-line marker), then the file pointer would move to column 0 row 1. Knowing the location of the file pointer and how it is moved around is important, especially if you will be writing to or reading from files that have fixed record formats with data fields starting and ending in specified column positions. Okay, enough about the file pointer. Let’s look at an example that ties together everything that we have talked about. In this example, I’ve written a VBScript that opens a file named myFile.txt, which resides in the root directory of my C: drive. If the file already exists, then the script opens it but if it does not already exist it will be created and opened.
' * Script Name: Script 8.vbs       *  

Option Explicit  

On Error Resume Next  

Dim fsoObject, open_File, target_File  

Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")  

target_File = "D:\ displayText.txt"  

' ********* Main processing section **********  

' Call a function that displays drive information  

Open_File()  

open_File.WriteLine "This line of data should be written to the text file."  

Close_File()  

' *********** Procedures go here *************  

' This function opens a file  

Function Open_File()  

 If (fsoObject.FileExists(target_File ) ) Then  

  Set open_File = fsoObject.OpenTextFile(target_File, 8 )  

 Else  

  Set open_File = fsoObject.OpenTextFile(target_File, 2, "True" )  

 End If  

End Function  

   

' This function closes a file  

Function Close_File()  

 open_File.Close()  

End Function
The file is opened using the forWriting constant ( with a value of 2 ) if it already exists. If the file does not exist, then the forAppending constant (with a value of 8 ) is specified to open the file and place the file pointer at the end of the file.If you take at look at the script’s main processing section you will see the following statement between a pair of function calls, which open and close the file.
open_File.WriteLine "This line of data should be written to the text file."
This statement writes one line of data to the file and executes a carriage return placing the file pointer in the first column of the following line. I’ll talk more about the use of this and other methods that are used to write data to files in just a bit. The last statement in the main processing section calls a function that executes the following statement.
open_File.Close()
This statement executed the FileSystemObject object’s close() method i to close the opened file. You must remember to close any file that you open before allowing your script to end. Failing to do so may cause an error the next time that you open the file because the end-of-file marker will not have been created.Run this script and open the myFile.txt file and you’ll see the following line of data.
This line of data should be written to the text file.
Writing to Files
As you just learned, you should always check for the existence of a file before creating it. Once opened, you have several different ways in which you can write text data to your files.One option is to write a specific number of characters at a time. This technique is best used when you need to write carefully formatted data to your files such as when you write reports with data that appears in columns. Another option for writing to a file is to write an entire line of data at a time. This technique is best used when your documents are more free-formed and is probably the option that you’ll use most often, especially if you plan to create log files in which you record error messages and other types of event information as your scripts execute.Finally, you might want to add blank lines to your files. Blank lines are especially useful for formatting your documents to improve their presentation and make them easier to read.
Adding Characters to a File

You can write a specific number of characters to a file at a time using the FileSystemObject object’s Write() method. This method does not automatically append a carriage return at the end of each write operation. Therefore, the next time a write operation occurs additional text is inserted immediately following the text written by the previous write operation.The following example demonstrates how you can use the Write() method to append text to an existing file.
Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")  

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )  

open_file.Write("Welcome to ")  

open_file.Write("KR Testing Solutions!")  

open_file.Close()
As you can see even though two separate write operations occurred, the text for both write operations was placed on the same line.
Adding a Line to a File

By replacing the Write() method with the FileSystemObject object’s WriteLine() method in the previous example, you can change the previous script to write data to the file a line at a time.
Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")  

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )  

open_file.WriteLine("Welcome to KR Testing Solutions!")  

open_file.Close()
The WriteLine() method automatically adds a carriage return to the end of each line returning the file pointer to the first column of the next line.
Adding Blank Lines to a File

If you want to format your text files with blank lines to create better looking reports or make them easier to read you can use the FileSystemObject object’s WriteBlankLines() method. When executed, this method writes a blank line to the file and executes a carriage return.The following example demonstrates how to use the WriteBlankLines() method to format the data in a small report.
Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")  

Set myCDrive = fsoObject.GetDrive("d:")  

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )  

   

open_file.WriteLine("------------------------------")  

open_file.WriteBlankLines(1)  

open_file.WriteLine("   My d: Drive Report   ")  

open_file.WriteBlankLines(1)  

open_file.WriteLine("------------------------------")  

   

open_file.WriteBlankLines(2)  

   

open_file.WriteLine("File System - " & myCDrive.FileSystem)  

open_file.WriteLine("Total Size - " & myCDrive.TotalSize)  

open_file.WriteLine("Free Space - " & myCDrive.AvailableSpace)  

   

open_file.Close()Reading from Files
Reading the contents of a file is handled in much the same way as writing to it. First, be sure that the file exists. If it does, then your script may open it. The next thing your script should do is use the TextStream object’s AtEndOfStream property to find out if the file has any data in it. After all, there is no point to trying to read an empty file. In fact, you should check the value of the AtEndOfStream property just before each read operation to be sure that your script has not reached the end of file marker (e.g., the end of the file). The first thing that you need to do to begin reading a text file is create an instance of the FileSystemObject and then use the FileSystemObject object’s OpenTextFile() method as shown here.
Set fsoObject = CreateObject("Scripting.FileSystemObject")  

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )
As you can see the forReading constant has been specified. Next you could set up a loop that runs until the AtEndOfStream property has a value of true (the end of the file is reached). During each iteration of the loop your script should read a line of text using the FileSystemObject object’s ReadLine() method as shown here.
Do while False = open_file.AtEndOfStream  

 WScript.Echo(open_file.ReadLine())     

Loop   

 
The preceding VBScript statements will process every line in the file, terminating when the end of file marker is reached. After your script is done reading the file, it can close it as shown here.
open_file.Close
If you put these lines of code together and ran them as a script using the CScript execution host you’d see output similar to the following.

C:\>CScript test.vbs  

Microsoft (R) Windows Script Host Version 5.6  

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.  

------------------------------  

   My d: Drive Report  

------------------------------  

File System - NTFS  

Total Size - 2146631554  

Free Space - 234554452  

C:\>  

 
In this example we read an entire file by reading it one line at a time. There are a number of other techniques for reading files. These include 
·         Skipping lines when reading a file
·         Reading a specified number of characters from a file
·         Reading an entire file in one operation
Skipping Portions of a File

If a file has headers or other information that you are not interested in reading you can always skip them and read only the portion of the file that interests you. For example, the file that we have been working with contains a five-line header followed by two blank lines after which the data in the report begins.You can use either of the following methods, both of which belong to the FileSystemObject, to skip text in a file. 
·         Skip(). Skip a specific number of characters
·         SkipLine(). Skips a lineThe Skip() method lets you supply a number indicating how many characters should be skipped. For example, the following statement would skip 25 characters in a file referenced as open_file.
open_file.Skip(25)
Unfortunately, the SkipLine() method does not allow you to pass it a number, indicating how many lines to skip. If you want to skip more than one line, you can wrap the method up inside a loop as demonstrated here.
For i = 1 to 7open_file.SkipLine()Next
Here the first seven lines of the file referenced as open_file would be skipped.
Reading Formatted Data

If your file has been formatted to contain fixed length data, then you have the option of reading it by character instead of by line. To do so you will use the FileSystemObject object’s Read() method.The following example demonstrates how to use this method. Here a reference is set up for a file named myfile.txt. Then a For loop is set up to skip the first seven lines of the file using the SkipLine() method. Next the Skip() method is used to skip the first fourteen characters on the eighth line. Finally the next four characters, beginning with the twenty-third character are read and then displayed. Then the file is closed.
Set fsoObject = CreateObject("Scripting.FileSystemObject")  

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )  

For i = 1 to 7  

 open_file.SkipLine()  

Next  

   

open_file.Skip(14)  

WScript.Echo("The file system in use on this drive is: "  

& open_file.Read(4))open_file.Close
Reading Entire Files
Another way in which you can read files is to read the entire file all at once using the FileSystemObject object’s ReadAll() method as demonstrated in the following example.
Set fsoObject = CreateObject("Scripting.FileSystemObject")  

Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )  

read_rpt = open_file.ReadAll()open_file.Close()MsgBox(read_rpt)
In this example, the entire file is read using a single statement, which assigns the data read by the ReadAll() method to a variable named read_rpt. The file is then closed and the value of read_rpt displayed using the VBScript MsgBox() function.
Performing File and Folder Administration
z
Managing your files and folders can involve a lot of work. Using VBScript and the WSH you can automate much of this work. For example, typical file and folder tasks involve copying or moving files and folders from one location to another in order to create backups or better organize them. Administration may also include deleting files once they have been processed or after they have reached a certain age.You can use methods belonging to the FileSystemObject to manage one or more files or folders at a time. FileSystemObject methods for handling files include 
· CopyFile(). Copies one or more files.
·         MoveFile(). Moves one or more files to a different location.
·         DeleteFile(). Delete one or more files.
·         FileExists(). Provides verification of whether a file contains data.The FileSystemObject also provides a number of methods that you can use to manage Windows folders, including 
·         CopyFolder(). Copies one or more folders.
·         MoveFolder(). Moves one or more folders to a different location.
·         DeleteFolder(). Deletes one or more folders.
·         FolderExists(). Provides verification of whether a folder exists.
·         CreateFolder(). Creates a new folder.Alternatively, you can also use the File and Folder objects to manage your files and folders instead of the FileSystemObject. These two objects share many of the same methods, including 
·         Copy(). Copies a file or folder to the specified location.
·         Delete(). Removes the specified file or folder.
·         Move(). Moves a file or folder to the specified location.

1 comment:

  1. Can we use QTP for Power Presentation files

    ReplyDelete