Sunday, April 29, 2012

Working With Processes


The article will discuss on how to close processes in QTP. First we will discuss the SystemUtil object and then later in the article few other approaches.
SystemUtil Object
SystemUtil is utility object provided by QTP. It can be used to launch or closes a process. Let’s look at various methods supported by this object
SystemUtil.Run file, [params], [dir], [op], [mode]
The Run method allows running a new process. The code below illustrates few example on how to launch a process using SystemUtil object
'Run internet explorer
SystemUtil.Run "iexplore.exe"

'Run internet explorer and open knowledgeinbox.com
SystemUtil.Run "iexplore.exe", "http://qa-knowledge.blogspot.in"

'Run a IE Process in Maximized window
Const SHOW_MAXIMIZED = 3 'Activates the window and displays it as a maximized window.
SystemUtil.Run "iexplore.exe", "http://qa-knowledge.blogspot.in", , , SHOW_MAXIMIZED

SystemUtil.CloseProcessByName (bsProcessName)

CloseProcessByName method allows closing a process by its name. The code below illustrates few examples  

'Close all internet explorer windows
closedCount = SystemUtil.CloseProcessByName("iexplore.exe")

'Display # of closed windows
MsgBox closedCount

The problem with using the above method is that it will also close Quality Center (QC) window even if script was launched from QC. This method should be used in case you are not concerned about running scripts from QC.

SystemUtil.CloseProcessByWndTitle (bsTitle, [bRegExp])

CloseProcessByWndTitle method allows closing a process by its title. The title can also be supplied as a regular expression by setting the bRegExp to True

'Launch a notepad window
SystemUtil.Run "notepad.exe"

'Close the window just launched using the exact title
SystemUtil.CloseProcessByWndTitle "Untitled - Notepad"

'Launch a notepad window
SystemUtil.Run "notepad.exe"

'Close the window just launched using a pattern string
SystemUtil.CloseProcessByWndTitle ".*Notepad", True

SystemUtil.CloseDescendentProcesses

CloseDescendentProcesses can be used to close any process launched by QTP. The code below illustrates the usage

'Launch explorer
SystemUtil.Run "iexplore.exe"

'Launch excel using COM
Set oXL = CreateObject("Excel.Application")
oXL.Visible = True

'Close processes launched by QTP. This will close
'the internet explorer and Excel as well
SystemUtil.CloseDescendentProcesses

This method is best suited to be used during the end of a script to cleanup any process left open.
Closing all open Browsers
Many times it’s required to close all open browsers at the start of the script. There are various ways of achieving this; one is to use the SystemUtil.CloseProcessByName method which we discussed earlier. But that approach is not generic as it won’t close other browsers that QTP does support (like firefox and netscape). We can come with a generic 3 lines code which can close all supported QTP browsers
'Check the existence of a browser and close it
'until no more browsers exist
While Browser("creationtime:=0").Exist(0)
   'Close the browser
    Browser("creationtime:=0").Close
 Wend
QTP assigns creation time to each browser based on the launch time of that browser. A browser started earlier will have a lower creationtime and a browser started at a later point of time will have a higher creationtime. So when we start closing the browser with creationtime:=0, other browser’s creationtime is decreased. Which means that the creationtime:=0 browser will always exist until there is no browser open. This approach of closing browsers suffers from 2 issues
  • QTP has a bug which makes it wait 10 second on Browser identified using creationtime when there is only one browser open. So above code will always take 10 secs to close the last browser
  • The code does not allow to ignore any specific browser (like Quality Center)
Though there another way by which can enumerate all open browser and close them in QTP and below demonstrates the same
'Create a description for browser
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
 Set oPage = Description.Create
oPage("micclass").Value = "Page"
 'Get all browsers
Set allBrowser = Desktop.ChildObjects(oBrowser)
 Dim i, iCount
 iCount = allBrowser.Count - 1
 For i = 0 To iCount
   'Get the page object from the browser
   Set oPg = allBrowser(i).ChildObjects(oPage)(0)
    'Get the URL of the
    If InStr(oPg.GetROProperty("title"), "Quality Center", vbTextCompare) = 0 Then
        'Close the browser
        allBrowser(i).Close
    End If
Next
 By now you must be wondering about the line
'Get the page object from the browser
Set oPg = allBrowser(i).ChildObjects(oPage)(0)


So why didn’t we use allBrowser(i).Page(“micclass:=Page”), well this a Bug or Limitation in QTP which does not allow using any further Test objects on objects returned from ChildObjects. This might be because of the fact that a QTP TestObject does not have any property or method as other Test Object. Ex – a Browser supports no method or property named Page. But QTP interprets that as way of hierarchy to decide where to look for that object.
Closing processes using WMI
Another way to close a process is to use Window management instrumentation (WMI)
'Name/IP of the computer
sComp = "."
 'Get the WMI object
Set WMI = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
 'Get collection of processes for with name iexplore.exe
Set allIE = WMI.ExecQuery("Select * from Win32_Process Where Name = 'iexplore.exe'")
 'Loop through each process and terminate it
For Each IE in allIE
    IE.Terminate()
Next
Above code can also be used to close any process on a remote machine by changing sComp to the IP of the remote machine
Closing Internet explorer using Shell
Let’s take a look at another way which is generic to VBScript and not dependent on QTP. For this we will use the COM object of “Shell.Application”. This COM library provides a collection of all open windows (Explorer + Internet Explorer). We can access each windows property and close if it is iexplore.exe process. The code below demonstrates the same
'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
 'Get all open windows collection
Set allWins = shlApp.Windows
 'Loop through each window and close if IE
For Each window In allWins
    If InStr(window.fullName, "iexplore.exe") Then
        'Close the IE window
        window.Quit
    End If
Next
The code above will only close alternate windows. This happens because we are loop through a collection of windows and closing a window in that collection reduces the collection and hence the for loop skips one window after closing a window. This issue can easily be resolved by adding the windows to be closed into an array and the closing them later
Dim windows2Close
 'Initialize with negative upper bound
ReDim windows2Close( -1)
 'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
 'Get all open windows collection
Set allWins = shlApp.Windows
 'Loop through each window and close if IE
For Each window In allWins
    'Close all IE windows but ignore Quality Center
    If InStr(window.fullName, "iexplore.exe") And InStr(Window.LocationURL, "/qcbin/") = 0 Then
         'Increase the array size by 1
        ReDim Preserve windows2Close(UBound(windows2Close) + 1)
        Set windows2Close(UBound(windows2Close)) = Window
    End If
Next
 'Loop through all array elements and close each window
For Each Window In windows2Close
    Window.Quit
Next
The above code shows how to ignore few internet explorers and close rest.









DateDiff Function in VBScript

The DateDiff function returns the number of intervals between two dates.

Syntax:

DateDiff(interval,date1,date2[,firstdayofweek[,firstweekofyear]])

ParameterDescription
intervalRequired. The interval you want to use to calculate the differences between date1 and date2Can take the following values:
  • yyyy - Year
  • q - Quarter
  • m - Month
  • y - Day of year
  • d - Day
  • w - Weekday
  • ww - Week of year
  • h - Hour
  • n - Minute
  • s - Second
date1,date2Required. Date expressions. Two dates you want to use in the calculation
firstdayofweekOptional. Specifies the day of the week.Can take the following values:
  • 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting
  • 1 = vbSunday - Sunday (default)
  • 2 = vbMonday - Monday
  • 3 = vbTuesday - Tuesday
  • 4 = vbWednesday - Wednesday
  • 5 = vbThursday - Thursday
  • 6 = vbFriday - Friday
  • 7 = vbSaturday - Saturday
firstweekofyearOptional. Specifies the first week of the year.Can take the following values:
  • 0 = vbUseSystem - Use National Language Support (NLS) API setting
  • 1 = vbFirstJan1 - Start with the week in which January 1 occurs (default)
  • 2 = vbFirstFourDays - Start with the week that has at least four days in the new year
  • 3 = vbFirstFullWeek - Start with the first full week of the new year


Example 1

The difference between January 31 2009, and January 31 2010:


<script type="text/vbscript">


fromDate="31-Jan-09 00:00:00"
toDate="31-Jan-10 23:59:00"
document.write(DateDiff("yyyy",fromDate,toDate) & "<br />")
document.write(DateDiff("q",fromDate,toDate) & "<br />")
document.write(DateDiff("m",fromDate,toDate) & "<br />")
document.write(DateDiff("y",fromDate,toDate) & "<br />")
document.write(DateDiff("d",fromDate,toDate) & "<br />")
document.write(DateDiff("w",fromDate,toDate) & "<br />")
document.write(DateDiff("ww",fromDate,toDate) & "<br />")
document.write(DateDiff("h",fromDate,toDate) & "<br />")
document.write(DateDiff("n",fromDate,toDate) & "<br />")
document.write(DateDiff("s",fromDate,toDate) & "<br />")


</script>


The output of the code above will be:


1
4
12
365
365
52
53
8783
527039
31622340



Example 2:

How many weeks (start on Monday),
between December 31 2009 and December 31 2012:

<script type="text/vbscript">

fromDate=CDate("2009/12/31")
toDate=CDate("2012/12/31")
document.write(DateDiff("w",fromDate,toDate,vbMonday))

</script>

The output of the code above will be:

156



Saturday, April 28, 2012

Dictionary Object

Object that stores data key, item pairs.

A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.
The following code illustrates how to create a Dictionary object:

Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
 
Add Method (Script Runtime):

Adds a key and item pair to a Dictionary object.

object.Add (key, item)

object

    Required. Always the name of a Dictionary object.
key

    Required. The key associated with the item being added.
item

    Required. The item associated with the key being added.

An error occurs if the key already exists.

The following example illustrates the use of the Add method. 

Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo" 

Exists Method (Script Runtime):

Returns true if a specified key exists in the Dictionary object, false if it does not.

  object
                      .Exists(
                      key
                      ) 

Object

    Required. Always the name of a Dictionary object.

Key

    Required. Key value being searched for in the Dictionary object.

The following example illustrates the use of the Exists method. 

Function KeyExists(k)
    Dim d, msg
    Set d = CreateObject("Scripting.Dictionary")
    d.Add "a", "Athens"
    d.Add "b", "Belgrade"
    d.Add "c", "Cairo"
    If d.Exists(k) Then
        msg = "Specified key exists."
    Else
        msg = "Specified key does not exist."
    End If
    KeyExists = msg
End Function

Items Method:

Returns an array containing all the items in a Dictionary object.

object.Items( ) 

The object is always the name of a Dictionary object.

The following code illustrates use of the Items method: 


Function DicDemo
   Dim a, d, i, s   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Items   ' Get the items.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "
" ' Create return string.
   Next
   DicDemo = s
End Function


Keys Method:

Returns an array containing all existing keys in a Dictionary object.

 object.Keys( ) 

The object is always the name of a Dictionary object.

The following code illustrates use of the Keys method: 

Function DicDemo
   Dim a, d, i   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Keys   ' Get the keys.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "
" ' Return results.
   Next
   DicDemo = s
End Function

Remove Method (Script Runtime):

Removes a key, item pair from a Dictionary object.

      object
                      .Remove(
                      key
                      )
                    
object

    Required. Always the name of a Dictionary object.
key

    Required. Key associated with the key, item pair you want to remove from the Dictionary object.

An error occurs if the specified key, item pair does not exist.

The following code illustrates use of the Remove method:

Dim a, d   ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
d.Remove("b")   ' Remove second pair.


RemoveAll Method:

The RemoveAll method removes all key, item pairs from a Dictionary object.

object.RemoveAll( ) 

The object is always the name of a Dictionary object.

The following code illustrates use of the RemoveAll method: 

Dim a, d, i   ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d.RemoveAll   ' Clear the dictionary.


Count Property (Script Runtime):

Returns the number of items in a collection or Dictionary object. Read-only.

                      object
                      .Count 

The object is always the name of one of the items in the Applies To list.

The following code illustrates use of the Count property: 


Function ShowKeys
   Dim a, d, i, s   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Keys   ' Get the keys.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "
" ' Create return string.
   Next
   ShowKeys = s
End Function


Item Property (Script Runtime):

Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write. 

object.Item(key)[ = newitem]

object

    Required. Always the name of a collection or Dictionary object.
key

    Required. Key associated with the item being retrieved or added.
newitem

    Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the new value associated with the specified key.

If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.

The following example illustrates the use of the Item property. 

Function ItemDemo
   Dim d   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   ItemDemo = d.Item("c")   ' Get the item.
End Function

Key Property:

Sets a key in a Dictionary object.

object.Key(key) = newkey

object

    Required. Always the name of a Dictionary object.
key

    Required. Key value being changed.
newkey

    Required. New value that replaces the specified key.

If key is not found when changing a key, a new key is created and its associated item is left empty.

The following example illustrates the use of the Key property:

Function DicDemo
   Dim d   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   d.Key("c") = "d"   ' Set key for "c" to "d".
   DicDemo = d.Item("d")   ' Return associate item.
End Function
CompareMode Property:

Sets and returns the comparison mode for comparing string keys in a Dictionary object.

object
                      .CompareMode[ = compare]

object

    Required. Always the name of a Dictionary object.
compare

    Optional. If provided, compare is a value representing the comparison mode. Acceptable values are 0 (Binary), 1 (Text), 2 (Database). Values greater than 2 can be used to refer to comparisons using specific Locale IDs (LCID).

An error occurs if you try to change the comparison mode of a Dictionary object that already contains data.

The following example illustrates the use of the CompareMode property: 

Dim d
Set d = CreateObject("Scripting.Dictionary")

d.CompareMode = vbTextCompare
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
' An error occurs on the next line because the key already exists.
' The comparison mode is Text, so the keys are case-insensitive.
d.Add "B", "Baltimore" 

Thursday, April 26, 2012

The Document Object

The Document object represents the current HTML page in the browser. The Document object also represents any object on the HTML page, such as a link, a form, a button, or an ActiveX object. The properties and methods for the Document object must be fully qualified when used. The Document object supports many properties and methods that modify the HTML page. These properties and methods, such as LinkColor and Write, must be used inline

when the HTML page is loading. These properties and methods cannot be called after the HTML page is loaded because the Internet Explorer parses the HTML only during page load. VBScript code can be executed inline as the load occurs. The following code shows an example where text is being written to an HTML page and the background color is being set to white:

<SCRIPT LANGUAGE="VBScript">
    Document.Write "<H2>Inline HTML modification</H2>"
    Document.BGColor="#FFFFFF"
</SCRIPT>
 
Executing inline code to modify an HTML page while it loads is known as immediate execution. Immediate execution is a valuable technique because it allows you to create web pages that are different each time they are loaded. As a simple example, the following code displays the date of the last update for the web page:
 
Document.Write "<P><CENTER>"
Document.Write "Page last updated"
Document.Write Document.LastModified
Document.Write "</CENTER><P>"  
 
This technique can be expanded to display new pictures or text on the basis of the current date, or even randomly. Tables below describe the properties and methods of the Document object.

Document Object Properties:
 

Property Type Description Usage
LinkColor String Returns or sets the link color. Accepts a string input representing the hexadecimal color value or a specific color command Document.LinkColor= "#FF0000" Document.LinkColor= "Red"
ALinkColor String Returns or sets the anchor color. Accepts a string input representing the hexadecimal color value or a specific color command. Document.ALinkColor="#FF0000" Document.ALinkColor="Red"
VLinkColor String Returns or sets the visited link color. Accepts a string input representing the hexadecimal color value or a specific color command. Document.VLinkColor="#FF0000" Document.VLinkColor="Red"
BGColor String Returns or sets the background color. Accepts a string input representing the hexadecimal color value or a specific color command. Document.BGColor="#FF0000" Document.BGColor="Red"
FGColor String Returns or sets the foreground color. Accepts a string input representing the hexadecimal color value or a specific color command. Document.FGColor = "#FF0000" Document.FGColor = "Red"
Anchors Object Returns an Anchors array. Set MyObject= Document.Anchors(1)
Links Object Returns a Links array. Set MyObject= Document.Links(1)
Forms Object Returns a Forms array. Set MyObject= Document.Forms(1)
Location String Returns a string representing the complete URL for the current document. MyVar= Document.Location
LastModified String Returns a string representing the date when the current page was last modified. MyVar= Document.LastModified
Title String Returns the read-only title of the current HTML page. MyVar= Document.Title
Cookie String Returns or sets the cookie for the current document. MyVar= Document.Cookie
Referrer String Returns the URL of the referring document. MyVar= Document.Referrer
Document Object Methods :
Method Return Type Description Usage
Write None Writes the given string into the current document. Document.Write "Hello"
WriteLn None Writes the given string into the current document with the addition of a newline character at the end. (This works only if the scripting section is surrounded by

tags.) 
Document.WriteLn "Hello"
Open None Opens the document stream for output. Document.Open
Close None Updates the screen to display all the strings written after the last Open method call. Document.Close
Clear None Closes the document output stream and writes the data to the screen. Document.Clear

Wednesday, April 25, 2012

TextStream Object:
Facilitates sequential access to file.
                      TextStream.{property  | method( )}
The property and method arguments can be any of the properties and methods associated with the TextStream object. Note that in actual usage, TextStream is replaced by a variable placeholder representing the TextStream object returned from the FileSystemObject.
The following example illustrates the use of the TextStream object.

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso, ts, fileObj, TextLine, FileName

Set fso = CreateObject("Scripting.FileSystemObject")

' Create the file, and obtain a file object for the file.
FileName = "c:\testfile.txt"
fso.CreateTextFile FileName
Set fileObj = fso.GetFile(FileName)

' Open a text stream for output.
Set ts = fileObj.OpenAsTextStream(ForWriting, TristateUseDefault)

' Write to the text stream.
ts.WriteLine "Hello World!"
ts.WriteLine "The quick brown fox"
ts.Close

' Open a text stream for input.
Set ts = fileObj.OpenAsTextStream(ForReading, TristateUseDefault)

' Read from the text stream and display the results.
Do While ts.AtEndOfStream <> True
    TextLine = ts.ReadLine
    Document.Write TextLine & "
"
Loop

ts.Close

Close Method (FileSystemObject):

Closes an open TextStream file.

The object is always the name of a TextStream object.

The following example illustrates use of the Close method.

Sub CreateAFile
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
   MyFile.WriteLine("This is a test.")
   MyFile.Close
End Sub

CreateTextFile Method:

Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.

object

    Required. Always the name of a FileSystemObject or Folder object.

filename

    Required. String expression that identifies the file to create.

overwrite

    Optional. Boolean value that indicates whether you can overwrite an existing file. The value is true if the file can be overwritten, false if it can't be overwritten. If omitted, existing files are not overwritten.

unicode

    Optional. Boolean value that indicates whether the file is created as a Unicode or ASCII file. The value is true if the file is created as a Unicode file, false if it's created as an ASCII file. If omitted, an ASCII file is assumed.

The following code illustrates how to use the CreateTextFile method to create and open a text file

Sub CreateAfile
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
   MyFile.WriteLine("This is a test.")
   MyFile.Close
End Sub

If the overwrite argument is false, or is not provided, for a filename that already exists, an error occurs. 



Read Method:

Reads a specified number of characters from a TextStream file and returns the resulting string.

object.Read(characters)

object

    Required. Always the name of a TextStream object.

characters

    Required. Number of characters you want to read from the file.

The following example illustrates how to use the Read method to read a six character header from a file and return the resulting string:

Function ReadTextFileTest
   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Dim fso, f, Msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   ReadTextFileTest = f.Read(5)
End Function

OpenTextFile Method:

Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.

object.OpenTextFile(filename[, iomode[, create[, format]]])

object

    Required. Object is always the name of a FileSystemObject.

filename

    Required. String expression that identifies the file to open.

iomode

    Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.

create

    Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value is True if a new file is created, False if it isn't created. If omitted, a new file isn't created.

format

    Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

The iomode argument can have any of the following settings:

ConstantValueDescription
ForReading1Open a file for reading only. You can't write to this file.
ForWriting2Open a file for writing.
ForAppending8Open a file and write to the end of the file.
The format argument can have any of the following settings:
ConstantValueDescription
TristateUseDefault-2Opens the file using the system default.
TristateTrue-1Opens the file as Unicode.
TristateFalse 0Opens the file as ASCII.


The following code illustrates the use of the OpenTextFile method.

Const ForReading = 1, ForWriting = 2, ForAppending = 8
' The following line contains constants for the OpenTextFile
' format argument, which is not used in the code below.
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso, MyFile, FileName, TextLine

Set fso = CreateObject("Scripting.FileSystemObject")

' Open the file for output.
FileName = "c:\testfile.txt"

Set MyFile = fso.OpenTextFile(FileName, ForWriting, True)

' Write to the file.
MyFile.WriteLine "Hello world!"
MyFile.WriteLine "The quick brown fox"
MyFile.Close

' Open the file for input.
Set MyFile = fso.OpenTextFile(FileName, ForReading)

' Read from the file and display the results.
Do While MyFile.AtEndOfStream <> True
    TextLine = MyFile.ReadLine
    Document.Write TextLine & "
"
Loop
MyFile.Close

OpenAsTextStream Method:

Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.

                      object
                      .OpenAsTextStream([iomode, [format]])

object

    Required. Always the name of a File object.

iomode

    Optional. Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending.

format

    Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

The iomode argument can have any of the following settings:
ConstantValueDescription
ForReading1Open a file for reading only. You can't write to this file.
ForWriting2Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
ForAppending8Open a file and write to the end of the file.
The format argument can have any of the following settings:
ConstantValueDescription
TristateUseDefault-2Opens the file using the system default.
TristateTrue-1Opens the file as Unicode.
TristateFalse 0Opens the file as ASCII.


The OpenAsTextStream method provides the same functionality as the OpenTextFile method of the FileSystemObject.
In addition, the OpenAsTextStream method can be used to write to a file.
The following code illustrates the use of the OpenAsTextStream method:

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso, ts, fileObj, TextLine

Set fso = CreateObject("Scripting.FileSystemObject")

' Create the file, and obtain a file object for the file.
FileName = "c:\testfile.txt"
fso.CreateTextFile FileName
Set fileObj = fso.GetFile(FileName)

' Open a text stream for output.
Set ts = fileObj.OpenAsTextStream(ForWriting, TristateUseDefault)

' Write to the text stream.
ts.WriteLine "Hello World!"
ts.WriteLine "The quick brown fox"
ts.Close

' Open a text stream for input.
Set ts = fileObj.OpenAsTextStream(ForReading, TristateUseDefault)

' Read from the text stream and display the results.
Do While ts.AtEndOfStream <> True
    TextLine = ts.ReadLine
    Document.Write TextLine & "
"
Loop

ts.Close

ReadAll Method:

Reads an entire TextStream file and returns the resulting string.

The object is always the name of a TextStream object.

For large files, using the ReadAll method wastes memory resources. Other techniques should be used to input a file, such as reading a file line by line.

The following example illustrates the use of the ReadAll method:

Function ReadAllTextFile
    Const ForReading = 1, ForWriting = 2
    Dim fso, MyFile, FileName

    Set fso = CreateObject("Scripting.FileSystemObject")

    ' Open the file for output.  
    FileName = "c:\testfile.txt"
    Set MyFile = fso.OpenTextFile(FileName, ForWriting, True)
   
    ' Write to the file.
    MyFile.Write "Header"
    MyFile.Write "1234567890987654321"
    MyFile.Close

    ' Open the file for input.
    Set MyFile = fso.OpenTextFile(FileName, ForReading)

    ' Read from the file.
    If MyFile.AtEndOfStream Then
        ReadAllTextFile = ""
    Else
        ReadAllTextFile = MyFile.ReadAll
    End If
End Function

ReadLine Method:

Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.

                      object.ReadLine( )

The object argument is always the name of a TextStream object.

The following example illustrates the use of the ReadLine method.

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, MyFile, FileName, TextLine

Set fso = CreateObject("Scripting.FileSystemObject")

' Open the file for output.
FileName = "c:\testfile.txt"

Set MyFile = fso.OpenTextFile(FileName, ForWriting, True)

' Write to the file.
MyFile.WriteLine "Hello world!"
MyFile.WriteLine "The quick brown fox"
MyFile.Close

' Open the file for input.
Set MyFile = fso.OpenTextFile(FileName, ForReading)

' Read from the file and display the results.
Do While MyFile.AtEndOfStream <> True
    TextLine = MyFile.ReadLine
    Document.Write TextLine & "
"
Loop
MyFile.Close

Skip Method:

Skips a specified number of characters when reading a TextStream file.

object.Skip(characters):

object

    Required. Always the name of a TextStream object.
characters

    Required. Number of characters to skip when reading a file.

Skipped characters are discarded.

The following example illustrates the use of the Skip method:


Function SkipTextFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   f.Skip(6)
   SkipTextFile =   f.ReadLine
End Function

SkipLine Method:

Skips the next line when reading a TextStream file.

object.SkipLine( )

The object is always the name of a TextStream object.

The following examples illustrate the use of the SkipLine method:

Function SkipLineInFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!" & vbCrLf & "VBScript is fun!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   f.SkipLine
   SkipLineInFile = f.ReadLine
End Function

Write Method (FileSystemObject):

Writes a specified string to a TextStream file.

object.Write(string)

object

    Required. Always the name of a TextStream object.

string

    Required. The text you want to write to the file.

Specified strings are written to the file with no intervening spaces or characters between each string. Use the WriteLine method to write a newline character or a string that ends with a newline character.

The following example illustrates the use of the Write method:

Function WriteToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   WriteToFile =   f.ReadLine
End Function

WriteBlankLines Method:

Writes a specified number of newline characters to a TextStream file.

    object.WriteBlankLines(lines)

object

    Required. Always the name of a TextStream object.
lines

    Required. Number of newline characters you want to write to the file.

The following example illustrates the use of the WriteBlankLines method:

Function WriteBlankLinesToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.WriteBlankLines 2
   f.WriteLine "Hello World!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   WriteBlankLinesToFile = f.ReadAll
End Function

WriteLine Method (FileSystemObject):

Writes a specified string and newline character to a TextStream file.

object

    Required. Always the name of a TextStream object.

string

    Optional. The text you want to write to the file. If omitted, a newline character is written to the file.

Function WriteLineToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.WriteLine "Hello world!"
   f.WriteLine "VBScript is fun!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   WriteLineToFile = f.ReadAll
End Function

AtEndOfLine Property (FileSystemObject):

Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file; false if it is not. Read-only.

 object.AtEndOfLine

The object is always the name of a TextStream object.

The AtEndOfLine property applies only to TextStream files that are open for reading; otherwise, an error occurs.

The following code illustrates the use of the AtEndOfLine property:

Function GetALine(filespec)
    Dim fso, file, s
    Const ForReading = 1

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile(filespec, ForReading, False)

    s = ""
    Do While file.AtEndOfLine <> True
        s = s & file.Read(1)
    Loop
    file.Close
    GetALine = s
End Function


AtEndOfStream Property (FileSystemObject):

Returns true if the file pointer is at the end of a TextStream file; false if it is not. Read-only.

 object.AtEndOfStream

The object is always the name of a TextStream object.

The AtEndOfStream property applies only to TextStream files that are open for reading, otherwise, an error occurs.

The following code illustrates the use of the AtEndOfStream property:

Function ReadEntireFile(filespec)
   Const ForReading = 1
   Dim fso, theFile, retstring
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set theFile = fso.OpenTextFile(filespec, ForReading, False)
   Do While theFile.AtEndOfStream <> True
      retstring = retstring & theFile.ReadLine
   Loop
   theFile.Close
   ReadEntireFile = retstring
End Function

Column Property (FileSystemObject):

Read-only property that returns the column number of the current character position in a TextStream file.

The object is always the name of a TextStream object.

After a newline character has been written, but before any other character is written, Column is equal to 1.

The following examples illustrates the use of the Column property:

Function GetColumn
   Const ForReading = 1, ForWriting = 2
   Dim fso, f, m
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   f.Close
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   m =   f.ReadLine
   GetColumn = f.Column
End Function


Line Property (FileSystemObject):

Read-only property that returns the current line number in a TextStream file.

object.Line

The object is always the name of a TextStream object.

After a file is initially opened and before anything is written, Line is equal to 1.

The following example illustrates the use of the Line property:

Function GetLine
   Const ForReading = 1, ForWriting = 2
   Dim fso, f, ra
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!" & vbCrLf & "VBScript is fun!" & vbCrLf
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   ra =   f.ReadAll
   GetLine = f.Line
End Function


StdIn,StdErr and stdout Property (WshScriptExec)

StdErr Property (WshScriptExec):
Exposes the stdin input stream of the Exec object.
Object

    WshScriptExec object.
 
 Object.StdIn

Use the StdIn property to pass data to a process started using Exec.
The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.

Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("test.bat")
input = ""

Do While True

     If Not oExec.StdOut.AtEndOfStream Then
          input = input & oExec.StdOut.Read(1)
          If InStr(input, "Press any key") <> 0 Then Exit Do
     End If
     WScript.Sleep 100
Loop

oExec.StdIn.Write VbCrLf

Do While oExec.Status <> 1
     WScript.Sleep 100
Loop

StdOut Property (WshScriptExec):

Exposes the write-only stdout output stream of the Exec object.
  Object.StdOut

Object

    WshScriptExec object.

The StdOut property contains a read-only copy of any information the script may have sent to the standard output.

StdErr Property (WshScriptExec):
 Object.StdErr
Object

    WshScriptExec object.

Use the StdErr property to retrieve data sent to the stderr stream from a process started with Exec.

The following code demonstrates the StdErr object by attempting to execute a non-existent command and displaying the results.
VBScript

Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("%comspec% /c dire")

Function ReadAllFromAny(oExec)

     If Not oExec.StdOut.AtEndOfStream Then
          ReadAllFromAny = oExec.StdOut.ReadAll
          Exit Function
     End If

     If Not oExec.StdErr.AtEndOfStream Then
          ReadAllFromAny = "STDERR: " + oExec.StdErr.ReadAll
          Exit Function
     End If
    
     ReadAllFromAny = -1
End Function

Dim allInput, tryCount

allInput = ""
tryCount = 0

Do While True

     Dim input
     input = ReadAllFromAny(oExec)

     If -1 = input Then
          If tryCount > 10 And oExec.Status = 1 Then
               Exit Do
          End If
          tryCount = tryCount + 1
          WScript.Sleep 100
     Else
          allInput = allInput & input
          tryCount = 0
     End If
Loop

WScript.Echo allInput




Tuesday, April 24, 2012

Echo Method

Outputs text to either a message box or the command console window.
object.Echo [Arg1] [,Arg2] [,Arg3] ... 
 
 object 
WScript object. 
Arg1, Arg2, Arg3 ...
Optional. String value indicating the list of items to be displayed.
The Echo method behaves differently depending on which WSH engine you are using.

WSH engineText Output
Wscript.exegraphical message box
Cscript.execommand console window
Each displayed item is separated with a space character. When using CScript.exe, each item is displayed with a newline character. If no items are provided as arguments to the Echo method, a blank line is output.

Example:

The following example uses the Echo Method to display the domain name, computer name, and user name for the current machine, and to display network mapping information for the drives and printers.

    language="VBScript"
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
         WScript.Echo 
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo 
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
      

        language="JScript"
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         WScript.Echo();
         WScript.Echo("Network drive mappings:");
         for(i=0; i< oDrives.Count(); i+=2){
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i+1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i=0; i< oPrinters.Count(); i+=2){
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i+1));
         }
      
 Equivalent using the property ".Stdout" as a TextStream                 
The following :
       WScript.Echo Args
is mostly equivalent to:
    WScript.Stdout.WriteLine Args
and give you access to other methods like
    Wscript.StdOut.Write Args
...except that the Stdout property is empty in Wscript (or in Internet Browser's scripts), where the Echo method uses replace it with a MessageBox (Alert in Javascript/ECMAScript). However, in CScript, the Stdout property allows better control of the output, and does not force you to output a newline break, and allows formatting its output (see also the TextStream class).

 Given that WSH does not offer any way to create TextStreams other than though the exposed StdIn, Stdout properties of the host (used internally by the Echo method), and through the FileSystemObject (FSO) class (by opening a file), the only way to format a string for display in a MessageBox compatible with the very limited Echo method in WScript, will be to use complex string formatting code ! Unfortunately, WSH still lacks support for TextStreams with output at least in memory (into a String object), in such a way that it would work transparently between CScript and Wscript with scripts written in JScript/ECMAScript or VBScript., and with the same facilities offered in VB for Applications and other .Net languages (C#, J#, ...). The workaround (using a FSO to create a temporary file or pipe then rereading it) is very inefficient (and also restricted due to FSO security restrictions, notably within the context of a browser). WSH engines should expose at least a method allowing to create a TextStream writing into a referenced String buffer (via concatenation).