Scripts for Windows Scripting Host

Dr. Dobb's Journal January 1999

Tools for your Win32 toolbox

By John Goalby

John is a senior software engineer for Intel. He can be contacted at jgoalby@ hotmail.com.

Microsoft's Windows Scripting Host (WSH) is a language-independent batch-processing language for Win32 that has been (or will be) bundled with Windows 98, NT Workstation 5.0, NT Server 5.0, and Internet Information Server 4.0 (IIS). Microsoft provides both Visual Basic/Scripting Edition and JavaScript scripting engines with WSH (WSH coding conventions are similar to those of Visual Basic). Additionally, WSH supports third-party ActiveX-based scripting engines for Perl, Tcl, REXX, Python, and other languages. WSH can be run from either Windows or the command shell-based host, using WSCRIPT.EXE or CSCRIPT.EXE, respectively.

From the developer's perspective, one nice thing about WSH is that you can script automation objects without needing a development environment. In other words, WSH is a convenient prototyping and discovery tool. For example, I use WSH for testing of all of my COM objects. If a COM object works with WSH, I'm confident it will work in most other situations. Likewise, I use WSH for testing ASP code before making web pages. This saves time, as I can avoid web infrastructure issues (HTML, HTTP, Security, and the like). Finally, I'm also using WSH to script a Java project. I first create all of my Java classes, then script them using WSH. This makes the project very flexible. Changes can be made easily and safely with a good object-oriented design.

In this article, I'll present a number of self-contained scripts that should be useful to software developers (as opposed to system administrators). Even though the scripts are written in VBScript, it should be straightforward to convert them to JScript.

Active Data Objects

Active Data Objects (ADO) are useful for programmatic access to ODBC-based databases. The script in Listing One (db.vbs) provides command-line access to ODBC databases. The script accepts a Data Source Name (DSN), username, and password to connect to the database. You also specify a SQL query that you would like to execute.

Listing Two shows this script in action (the database comes with the Active Server Page install for IIS). Listing One is simple because of VBScript's ability to enumerate collections. The ADO recordset (objRS) is traversed using this part of Listing One:

Do While Not objRS.Eof
 For Each oField In objRS.Fields
WScript.Echo oField.Name & " : " & oField.Value
 Next
 objRS.MoveNext
Loop

You could enhance this script to provide other database querying features, such as database metadata. Likewise, a listing of the available data source names on the system would be useful, as would a listing of tables available within a given database. You would then be able to find out all about a database from a script.

Accessing Java

Being able to access Java from WSH adds a variety of capabilities to your scripting repertoire, including extensive network programming support, flexible dynamic user interfaces, compression code, and threads, to name a few. To access Java objects from WSH (or, for that matter, any active script host), use the JavaReg tool that comes with the Microsoft Java SDK. To access Java objects, simply issue the command javareg /register /class:JUtil /progid:Java.Jutil to expose the class called JUtil as a COM object with the Program ID Java.JUtil.

The example I present here demonstrates how you can access web pages from your scripts. In the process, I'll utilize the Java helper class JUtil.java (available electronically; see "Resource Center," page 5). As you can see from the script in Listing Three (getwebpage.vbs), I invoke the method getWebPage of JUtil. This method gets the web page requested by the only parameter. As Listing Four shows, the return value is the content of the retrieved web page that is output directly to the console.

The reason for using a helper class rather than registering the Java URL class directly, is partly due to URL requiring a parameter in its constructor. Unfortunately, the CreateObject function does not allow for a parameter to be passed when an object is created.

File Manipulation

The script in Listing Five (favorites.vbs) reads your Internet Explorer Favorites, then checks to see if IE can access the web site for each entry. This is useful for determining dead links within your Favorites. I again utilize my Java helper class. The getWebPageResponse method (see JUtil.java, available electronically) lets you get the HTTP response code from a web request. Table 1 shows the common HTTP return codes.

In addition to letting you determine that a web page no longer exists, the HTTP response also shows you when a page has moved and the link needs to be updated. Since many sites automatically redirect you (for load balancing, cookie setting, or whatever), the script has a NoAutoRedirect option for turning off automatic redirects.

Since Listing Five can take a while to execute (depending upon the speed of your network), I implemented a simple progress bar in Java and added it to the JUtil helper class (also available electronically). This lets you see that something is happening.

Listing Five also demonstrates file manipulation. The Favorites special folder is obtained and used to recursively read all of the URL files that reside there. When the URL file is retrieved, a check is made to see if the page is still accessible. The code to retrieve a special folder for the current user is made simple by WSH. Listing Six displays all of the special folders on a machine. (SSL is not currently supported within Java. If you require SSL, you can purchase a third-party SSL library, or create a COM object that exposes the WinInet API.)

The file-manipulation script can be enhanced in a number of ways. You could program it to move dead links to another folder within the Favorites for later use. Alternatively, you could change the name shown in the Favorites list to indicate accessibility. You could also indicate how long it took for the request to complete. This would save you time by directing you to sites that load quickly and avoiding broken links. For example:

[FAST] Example Page 1
[NOT FOUND] Example Page 2
[SLOW] Example Page 3
[SLOW] Example Page 4

COM Servers

You can also use WSH to test COM servers and provide a handy text-coloring class. Listing Seven (cdir.vbs) makes use of a COM server to provide colored directory output. (You'll need to register ColorHelper.dll, available electronically, on your machine using regsvr32 ColorHelper.dll.)

The coloring of the files is currently based on the extension of the files but could just as easily be based on the other attributes of the files. (The NT COLOR utility resets colors.)

This script could be enhanced in a number of ways. To truly make it a useful replacement for the existing dir command, you would have to duplicate most of the existing functions such as ordering of output, wildcard matching, and recursing subdirectories.

COM programmers should be aware that VBScript has limitations. Everything in VBScript must be represented as a VARIANT. If you have multiple out parameters in your COM server, they must all be VARIANTS. Also, the entries within SAFEARRAY's must be VARIANTS. Multiple out parameters are supported in VBScript 3.0.

WSH is useful for quickly and easily testing COM objects. The absence of an extra compile step and bulky development environment also speeds things up. I find it useful to keep my scripts with my COM server (by checking them into the same project if you have a version control system). This lets me quickly find the script to test my object when I make any modifications. This also provides a starting point for regression testing.

Coloring can be used wherever emphasis is needed. For instance, the Favorites script (Listing Five) could be enhanced to output good links in green, redirects in yellow, and serious problems in red.

If you are interested in adding color to your Win32 console applications, the Win32 API function used to change the console text color is SetConsoleTextAttribute.

Developer Studio

You can use scripts to manipulate Microsoft's Developer Studio automation objects. The object model gives you access to the projects within a workspace. Unfortunately, you cannot programmatically access each of the files within the project. You only have access to the open documents, which are dependent upon how you saved the project. Hopefully, the object model will be improved in later versions.

Listing Eight shows the steps that display the configurations for a given project passed on the command line. The script in Listing Nine (devstu.vbs) opens the passed-in project, then builds each of the configurations contained in that project. This gives you a way to rebuild everything for particular configurations easily. Accessing the Developer Studio objects from WSH does not provide any real advantages over makefiles. However, automating Developer Studio can be useful in situations where, say, you want to access other scripting hosts such as ASP to let users invoke a build from a web page.

Conclusion

As you can see from these examples, the Windows Scripting Host is a powerful tool for developers, as well as system administrators. In addition to the scripts presented here, I've provided additional scripts electronically for tasks such as using Microsoft Outlook, managing Microsoft Agent Controls, customizing Visual SourceSafe (Microsoft's control system), and managing e-mail. These, too, should be important additions to any developer's toolbox.

DDJ

Listing One

' ==================================================================' Script to exectute a query against an ADO compliant database
' ==================================================================
' ------------------------------------------------------------------
' Call the main subroutine
' ------------------------------------------------------------------
call Main()
' ------------------------------------------------------------------
' We are finishing now
' ------------------------------------------------------------------
WScript.Quit (0)
' ------------------------------------------------------------------
' The main subroutine
' ------------------------------------------------------------------
Sub Main
    ' --------------------------------------------------------------
    ' Get an object of the params passed in to this script
    ' --------------------------------------------------------------
    Set objArgs = Wscript.Arguments
    ' --------------------------------------------------------------
    ' Check the arguments passed
    ' --------------------------------------------------------------
    If objArgs.Count < 1 Then
        WScript.Echo "Please specify a query to execute."
        WScript.Echo ""
        WScript.Echo "Valid paramters are "
        WScript.Echo "    DSN:<DSN>"
        WScript.Echo "    User:<User name>"
        WScript.Echo "    Password:<Password>"
        WScript.Echo "    Query:<SQL Query>"
        WScript.Echo ""
        WScript.Echo "If there is no keyword the parameter is " &_
                     "assumed to be the query."
        WScript.Echo ""
        WScript.Echo "Example : DB DSN:MyDSN ""User:AUser"" """ &_ 
                     "select * from table"""
        WScript.Quit (1)
    End If
    ' --------------------------------------------------------------
    ' This is where you could set defaults
    ' --------------------------------------------------------------
    strDSN = ""
    strUser = ""
    strPassword = ""
    strQuery = ""
    ' --------------------------------------------------------------
    ' For each of the arguments passed see if they start with a 
    ' keyword and a : If so get the remaining text from the param
    ' --------------------------------------------------------------
    For I = 0 to objArgs.Count - 1
        strArg = objArgs(I)
        If (Left (UCase (strArg), 4) = "DSN:") Then
            strDSN = Right (strArg, Len (strArg) - 4)
        ElseIf (Left (UCase (strArg), 5) = "USER:") Then
            strUser = Right (strArg, Len (strArg) - 5)
        ElseIf (Left (UCase (strArg), 9) = "PASSWORD:") Then
            strPassword = Right (strArg, Len (strArg) - 9)
        ElseIf (Left (UCase (strArg), 6) = "QUERY:") Then
            strQuery = Right (strArg, Len (strArg) - 6)
        Else
            strQuery = strArg
        End If
    Next 
    ' --------------------------------------------------------------
    ' Check that we have something to do
    ' --------------------------------------------------------------
    If (Len (strQuery) = 0) Then
        WScript.Echo "Please specify a query to execute"
        WScript.Quit (2)
    End If
    ' --------------------------------------------------------------
    ' Create an ADO connection
    ' --------------------------------------------------------------
    Set objDB = WScript.CreateObject("ADODB.Connection")
    ' --------------------------------------------------------------
    ' See if can connect to the passed in DSN using passed username 
    ' and password
    ' --------------------------------------------------------------
    objDB.open strDSN, strUser, strPassword
    ' --------------------------------------------------------------
    ' Execute the query passed
    ' --------------------------------------------------------------
    Set objRS = objDB.Execute (strQuery)
    ' --------------------------------------------------------------
    ' Check to make sure that open state
    ' --------------------------------------------------------------
    if objRS.State = 1 Then
        ' ----------------------------------------------------------
        ' Go through recordset and output each field returned
        ' ----------------------------------------------------------
        Do While Not objRS.Eof
            For Each oField In objRS.Fields
                if oField = "" or IsNull(oField) Then
                    WScript.Echo ""
                Else
                    WScript.Echo oField.Name & " : " & oField.Value
                End If
            Next
            ' ------------------------------------------------------
            ' Skip to next record and space between records
            ' ------------------------------------------------------
            objRS.MoveNext
            WScript.Echo ""
        Loop
    else
        WScript.Echo "Nothing returned"
    End if

' Clear objects ' -------------------------------------------------------------- Set objDB = Nothing End Sub ' ------------------------------------------------------------------ ' End of script ' ------------------------------------------------------------------

Back to Article

Listing Two

>DB DSN:ADOSamples "select * from Products where UnitPrice > 450"ProductID : 14
ProductCode : AW535-11
ProductType : Tent
ProductIntroductionDate : 5/29/96
ProductName : Galaxy
ProductDescription : durable 3-person all-purpose tent, maximum headroom, no-leak floor, beige/purple (bp)
ProductImageURL : /advworks/multimedia/catalog/camping/dtents19.gif
UnitPrice : 535
OnSale : False

Back to Article

Listing Three

' ==================================================================' Script to get the contents of a web page
' ==================================================================
' ------------------------------------------------------------------
' Call the main subroutine
' ------------------------------------------------------------------
call Main()
' ------------------------------------------------------------------
' We are finishing now
' ------------------------------------------------------------------
WScript.Quit (0)
' ------------------------------------------------------------------
' The main subroutine
' ------------------------------------------------------------------
Sub Main
    ' --------------------------------------------------------------
    ' Get an object of the params passed in to this script
    ' --------------------------------------------------------------
    Set objArgs = Wscript.Arguments
    ' --------------------------------------------------------------
    ' Check the arguments passed, only have 1 param in this script
    ' --------------------------------------------------------------
    If objArgs.Count <> 1 Then
        ' ------------------------------------------------------
        ' Tell the user the usage of this script
        ' ------------------------------------------------------
        WScript.Echo "Please pass only 1 param, " &_
            "the URL that you would like retrieved"
        WScript.Quit (1)
    End If
    ' ------------------------------------------------------------------
    ' Create the Java helper object
    ' ------------------------------------------------------------------
    Set objJUtil = CreateObject ("Java.JUtil")
    ' --------------------------------------------------------------
    ' Get the actual web page and output to the console
    ' --------------------------------------------------------------
    strResponseText = objJUtil.getWebPage (objArgs(0))
    WScript.Echo strResponseText
    ' ------------------------------------------------------------------
    ' Clear up
    ' ------------------------------------------------------------------
    Set objJUtil = Nothing
End Sub
' ------------------------------------------------------------------
' End of script
' ------------------------------------------------------------------

Back to Article

Listing Four

strResponseText = objJUtil.getWebPage (objArgs(0))WScript.Echo strResponseText

Back to Article

Listing Five

favorites.vbs' ==================================================================
' Script to check your IE favorites for dead links.
' ==================================================================
' ------------------------------------------------------------------
' Create the Java helper object
' ------------------------------------------------------------------
Set g_objJava = CreateObject ("Java.JUtil")
' ------------------------------------------------------------------
' Access to the file system
' ------------------------------------------------------------------
Set g_objFSO = CreateObject ("Scripting.FileSystemObject")
' ------------------------------------------------------------------
' A couple of global booleans, one for HTTP redirection and the 
' other to determine if you want to see that progress is happening.
' ------------------------------------------------------------------
g_bRedirect = true
' ------------------------------------------------------------------
' Call the main subroutine
' ------------------------------------------------------------------
call Main()
' ------------------------------------------------------------------
' Clear up
' ------------------------------------------------------------------
Set g_objJava = Nothing
Set g_objFSO = Nothing
' ------------------------------------------------------------------
' We are finishing now
' ------------------------------------------------------------------
WScript.Quit (0)
' ------------------------------------------------------------------
' The main subroutine
' ------------------------------------------------------------------
Sub Main
    ' --------------------------------------------------------------
    ' Get an object of the params passed in to this script
    ' --------------------------------------------------------------
    Set objArgs = Wscript.Arguments
    ' --------------------------------------------------------------
    ' Check the arguments passed, only have 1 param in this script
    ' --------------------------------------------------------------
    If objArgs.Count = 1 Then
        ' ----------------------------------------------------------
        ' Determine if the user wants to stop automatic redirects
        ' ----------------------------------------------------------
        If (UCase (objArgs(0)) = UCase ("NoAutoRedirect")) Then
            g_bRedirect = false
        Else
            ' ------------------------------------------------------
            ' Tell the user the usage of this script
            ' ------------------------------------------------------
            WScript.Echo "Please pass only 1 param, " &_
                """NoAutoRedirect"" for turning off auto redirect"
            WScript.Quit (1)
        End If
    Else
        ' ----------------------------------------------------------
        ' Too many params
        ' ----------------------------------------------------------
        If objArgs.Count > 1 Then
            ' ------------------------------------------------------
            ' Tell the user the usage of this script
            ' ------------------------------------------------------
            WScript.Echo "Please pass only 1 param, " &_
                """NoAutoRedirect"" for turning off auto redirect"
            WScript.Quit (2)
        End If
    End If
    ' --------------------------------------------------------------
    ' Get the location of the Favorites Special Folder
    ' --------------------------------------------------------------
    Set objShell = WScript.CreateObject ("WScript.Shell")
    strFavesPath = objShell.SpecialFolders ("Favorites")
    ' --------------------------------------------------------------
    ' Get the physical folder for the favorites
    ' --------------------------------------------------------------
    Set objRootFolder = g_objFSO.GetFolder (strFavesPath)
    ' --------------------------------------------------------------
    ' Indicate that something is going on, color is rgb value
    ' --------------------------------------------------------------
    g_objJava.setFillColor (100)
    g_objJava.showProgress "Favorites progress", 250, 50
    ' --------------------------------------------------------------
    ' Process all folders below this one
    ' --------------------------------------------------------------
    ProcessFolders (objRootFolder)
    ' --------------------------------------------------------------
    ' Indicate that something is going on
    ' --------------------------------------------------------------
    g_objJava.hideProgress
    ' --------------------------------------------------------------
    ' Clear up
    ' --------------------------------------------------------------
    Set g_objShell = Nothing
End Sub
' ------------------------------------------------------------------
' Process a folder, process all files in passed folder then process 
' all of the subfolders.
' ------------------------------------------------------------------
Sub ProcessFolders (ByVal objRootFolder)
    ProcessFiles (objRootFolder)
    For Each objCurFolder In objRootFolder.SubFolders
        ProcessFolders (objCurFolder)
    Next
End Sub
' ------------------------------------------------------------------
' Process files in the passed folder
' ------------------------------------------------------------------
Sub ProcessFiles (ByVal objCurFolder)
    For Each objCurFile In objCurFolder.Files
        ' ----------------------------------------------------------
        ' Only deal with files that have a .URL extension
        ' ----------------------------------------------------------
        If (UCase (g_objFSO.GetExtensionName (objCurFile)) _
                    = "URL") Then
            ' ------------------------------------------------------
            ' Open the URL file
            ' ------------------------------------------------------
            Set objURLFile = g_objFSO.OpenTextFile (objCurFile)
            ' ------------------------------------------------------
            ' Go through the file looking at each line
            ' ------------------------------------------------------
            Do While objURLFile.AtEndOfStream <> True
                strURLLine = objURLFile.ReadLine
                ' --------------------------------------------------
                ' Match line that starts with URL string
                ' --------------------------------------------------
                If (UCase (Left (strURLLine, 3)) = "URL") Then
                    ' ----------------------------------------------
                    ' Get the URL from the text
                    ' ----------------------------------------------
                    strURL = Right (strURLLine, Len (strURLLine) - 4)
                    ' ----------------------------------------------
                    ' Get the response from the web page
                    ' ----------------------------------------------
                    iResponseCode = g_objJava.getWebPageResponse _
                                                (strURL, g_bRedirect)
                    ' ----------------------------------------------
                    ' If not a good response code then tell user
                    ' ----------------------------------------------
                    If (iResponseCode <> 200) Then
                        WScript.Echo _
                            "------------------------------------"
                        WScript.Echo iResponseCode
                        WScript.Echo objCurFile
                        WScript.Echo strURL
                        WScript.Echo _
                            "------------------------------------"
                    End If
                    ' ----------------------------------------------
                    ' Show progress
                    ' ----------------------------------------------
                    g_objJava.updateProgress
                End If
            Loop
            ' ------------------------------------------------------
            ' Close the URL file
            ' ------------------------------------------------------
            objURLFile.Close
        End If
    Next
End Sub
' ------------------------------------------------------------------
' End of script
' ------------------------------------------------------------------

Back to Article

Listing Six

set objShell = WScript.CreateObject ("WScript.Shell")set objSF = objShell.SpecialFolders
For Each Folder In objSF
    WScript.Echo Folder
Next

Back to Article

Listing Seven

' ==================================================================' Script to color filenames based on their extension
' ==================================================================
' ------------------------------------------------------------------
' Access to the file system
' ------------------------------------------------------------------
Set g_objFSO = CreateObject ("Scripting.FileSystemObject")
' ------------------------------------------------------------------
' Create instance of Console color COM server
' ------------------------------------------------------------------
Set objColor = WScript.CreateObject ("ConsoleColor.ConsoleColor")
' ------------------------------------------------------------------
' Call the main subroutine
' ------------------------------------------------------------------
call Main()
' ------------------------------------------------------------------
' Clear up
' ------------------------------------------------------------------
Set objColor = Nothing
Set g_objFSO = Nothing
' ------------------------------------------------------------------
' We are finishing now
' ------------------------------------------------------------------
WScript.Quit (0)
' ------------------------------------------------------------------
' The main subroutine
' ------------------------------------------------------------------
Sub Main
    ' --------------------------------------------------------------
    ' Get an object of the params passed in to this script
    ' --------------------------------------------------------------
    Set objArgs = Wscript.Arguments
    ' --------------------------------------------------------------
    ' Default to the current directory
    ' --------------------------------------------------------------
    strParam = "."
    ' --------------------------------------------------------------
    ' Check the arguments passed, if 1 then take it
    ' --------------------------------------------------------------
    If objArgs.Count >= 1 Then
        strParam = objArgs(0)
    End If
    ' --------------------------------------------------------------
    ' Blank line to output
    ' --------------------------------------------------------------
    WScript.Echo ""
    ' --------------------------------------------------------------
    ' Save the current color settings
    ' --------------------------------------------------------------
    wVal = objColor.GetCurrentColor()
    ' --------------------------------------------------------------
    ' Get the physical folder for the favorites
    ' --------------------------------------------------------------
    Set objCurFolder = g_objFSO.GetFolder (strParam)
    ' --------------------------------------------------------------
    ' Holder for the longest filename so that can line them up
    ' --------------------------------------------------------------
    iCurFileLen = 0
    ' --------------------------------------------------------------
    ' For each folder in the obtained folder work out longest name
    ' --------------------------------------------------------------
    For Each aFolder In objCurFolder.SubFolders
        If (Len (aFolder .Name) > iCurFileLen) Then
            iCurFileLen = Len (aFolder.Name)
        End If
    Next
    ' --------------------------------------------------------------
    ' For each file in the obtained folder work out longest name
    ' --------------------------------------------------------------
    For Each objCurFile In objCurFolder.Files
        If (Len (objCurFile.Name) > iCurFileLen) Then
            iCurFileLen = Len (objCurFile.Name)
        End If
    Next
    ' --------------------------------------------------------------
    ' For each folder in the obtained folder
    ' --------------------------------------------------------------
    For Each aFolder In objCurFolder.SubFolders
        ' ----------------------------------------------------------
        ' Get the folder attributes
        ' ----------------------------------------------------------
        strAttr = getAttribute (aFolder.Attributes)
        ' ----------------------------------------------------------
        ' Store the name
        ' ----------------------------------------------------------
        strFileName = aFolder.Name
        ' ----------------------------------------------------------
        ' Add spaces to the end of the name so all the same length
        ' ----------------------------------------------------------
        For iIndex = Len(aFolder.Name) To iCurFileLen + 1
            strFileName = strFileName + " "
        Next
        ' ----------------------------------------------------------
        ' Output the information we have on the folder
        ' ----------------------------------------------------------
        WScript.Echo strAttr & aFolder.DateLastModified &_
                     vbtab & strSize & vbtab &_
                     strFileName & aFolder.Type 
    Next
    ' --------------------------------------------------------------
    ' For each file in the obtained folder
    ' --------------------------------------------------------------
    For Each objCurFile In objCurFolder.Files
        ' ----------------------------------------------------------
        ' Change the colors back to original
        ' ----------------------------------------------------------
        objColor.SetColor (wval)
        ' ----------------------------------------------------------
        ' Depending upon the extension color the output, you can 
        ' choose to do this a more extensible way using arrays 
        ' if you like.
        ' ----------------------------------------------------------
        strExtension = g_objFSO.GetExtensionName (objCurFile)
        If (UCase (strExtension) = "VBS") Then
            objColor.SetForegroundColor (12)
        ElseIf (UCase (strExtension) = "DOC") Then
            objColor.SetForegroundColor (14)
        ElseIf (UCase (strExtension) = "JAVA") Then
            objColor.SetForegroundColor (10)
        ElseIf (UCase (strExtension) = "TXT") Then
            objColor.SetForegroundColor (14)
        ElseIf (UCase (strExtension) = "BAT") Then
            objColor.SetForegroundColor (11)
        ElseIf (UCase (strExtension) = "SYS") Then
            objColor.SetForegroundColor (13)
        ElseIf (UCase (strExtension) = "DLL") Then
            objColor.SetForegroundColor (15)
        ElseIf (UCase (strExtension) = "CLASS") Then
            objColor.SetForegroundColor (9)
        ElseIf (UCase (strExtension) = "COM") Then
            objColor.SetForegroundColor (12)
        ElseIf (UCase (strExtension) = "ZIP") Then
            objColor.SetForegroundColor (11)
        End If
        ' ----------------------------------------------------------
        ' Get the file attributes
        ' ----------------------------------------------------------
        strAttr = getAttribute (objCurFile.Attributes)
        ' ----------------------------------------------------------
        ' Store the name
        ' ----------------------------------------------------------
        strFileName = objCurFile.Name
        ' ----------------------------------------------------------
        ' Add spaces to the end of the name so all the same length
        ' ----------------------------------------------------------
        For iIndex = Len(objCurFile.Name) To iCurFileLen + 1
            strFileName = strFileName + " "
        Next
        ' ----------------------------------------------------------
        ' Format the size to have the thousand separator
        ' ----------------------------------------------------------
        strSize = FormatNumber (objCurFile.Size, 0, false, false, true)
        ' ----------------------------------------------------------
        ' Output the information we have on the file
        ' ----------------------------------------------------------
        WScript.Echo strAttr & objCurFile.DateLastModified &_
                     vbtab & strSize & vbtab &_
                     strFileName & objCurFile.Type 
    Next
    ' --------------------------------------------------------------
    ' Change the colors back to original
    ' --------------------------------------------------------------
    objColor.SetColor (wval)
End Sub
' ------------------------------------------------------------------
' Format a string for the given attribute value
' 1    = read only              r
' 2    = hidden                 h
' 4    = system                 s
' 8    = volume         v                       
' 16   = directory              d
' 32   = archive                a
' 2048 = compressed (NT Only)   c
' Output will be in the form "[ cadshr ]"

, ----------------------------------- Function getAttribute (iAttr) strAttr = "[ " If (iAttr AND 2048) Then strAttr = strAttr + "c" else strAttr = strAttr + " " End If If (iAttr AND 32) Then strAttr = strAttr + "a" else strAttr = strAttr + " " End If If (iAttr AND 16) Then strAttr = strAttr + "d" else strAttr = strAttr + " " End If If (iAttr AND 8) Then strAttr = strAttr + "v" else strAttr = strAttr + " " End If If (iAttr AND 4) Then strAttr = strAttr + "s" else strAttr = strAttr + " " End If If (iAttr AND 2) Then strAttr = strAttr + "h" else strAttr = strAttr + " " End If If (iAttr AND 1) Then strAttr = strAttr + "r" else strAttr = strAttr + " " End If strAttr = strAttr + "] " getAttribute = strAttr End Function ' ------------------------------------------------------------------ ' End of script ' ------------------------------------------------------------------

Back to Article

Listing Eight

objDevStudio.Documents.Open objArgs(0)

Set objProjects = objDevStudio.Projects

If (objProjects.Count = 0) Then WScript.Echo "No current project" Else For Each aProject in objProjects WScript.Echo aProject.Name WScript.Echo aProject.Type Next End If

Back to Article

Listing Nine

' ==================================================================' Script to illustrate use of automating DevStudio
' ==================================================================
' ------------------------------------------------------------------
' Call the main subroutine
' ------------------------------------------------------------------
call Main()
' ------------------------------------------------------------------
' We are finishing now
' ------------------------------------------------------------------
WScript.Quit (0)
' ------------------------------------------------------------------
' The main subroutine
' ------------------------------------------------------------------
Sub Main
    ' --------------------------------------------------------------
    ' Get an object of the params passed in to this script
    ' --------------------------------------------------------------
    Set objArgs = Wscript.Arguments
    ' --------------------------------------------------------------
    ' Check the arguments passed, only have 1 param in this script
    ' --------------------------------------------------------------
    If objArgs.Count <> 1 Then
        WScript.Echo "Please pass only 1 param, the Developer " &_
                        "Studio project (dsw) to open"
        WScript.Quit (1)
    End If
    ' --------------------------------------------------------------
    ' Create an instance of Developer Studio automation server
    ' --------------------------------------------------------------
    Set objDevStudio = CreateObject ("MSDev.Application")
    ' --------------------------------------------------------------
    ' We don't want it to be visible, make it visible for debugging
    ' --------------------------------------------------------------
    objDevStudio.Visible = false
    ' --------------------------------------------------------------
    ' Open the specified project
    ' --------------------------------------------------------------
    objDevStudio.Documents.Open objArgs(0)
    ' --------------------------------------------------------------
    ' Get the projects object
    ' --------------------------------------------------------------
    Set objProjects = objDevStudio.Projects
    ' --------------------------------------------------------------
    ' Check that we have some projects
    ' --------------------------------------------------------------
    If (objProjects.Count = 0) Then
        WScript.Echo "No current project"
    Else
        ' ----------------------------------------------------------
        ' For each of the projects
        ' ----------------------------------------------------------
        For Each aProject in objProjects
            ' ------------------------------------------------------
            ' Output name and type
            ' ------------------------------------------------------
            WScript.Echo aProject.Name
            WScript.Echo aProject.Type
            ' ------------------------------------------------------
            ' If a buildable project output condifurations
            ' ------------------------------------------------------
            If (aProject.Type = "Build") Then
                For Each myConfiguration in aProject.Configurations
                    WScript.Echo myConfiguration.Name
                Next
            End If
        Next
    End If
    ' --------------------------------------------------------------
    ' Get the current documents 
    ' --------------------------------------------------------------
    Set objDocuments = objDevStudio.Documents
    ' --------------------------------------------------------------
    ' Check that we have some documents open
    ' --------------------------------------------------------------
    If (objDocuments.Count = 0) Then
        WScript.Echo "No documents"
    Else
        ' ----------------------------------------------------------
        ' Output the name and type of the document
        ' ----------------------------------------------------------
        For Each aDoc in objDocuments
                WScript.Echo aDoc.Name
                WScript.Echo aDoc.Type
        Next
    End If
    ' --------------------------------------------------------------
    ' Close developer studion and Clean up
    ' --------------------------------------------------------------
    objDevStudio.Quit
    Set objDevStudio = Nothing
End Sub
' ------------------------------------------------------------------
' End of script
' ------------------------------------------------------------------

Back to Article


Copyright © 1999, Dr. Dobb's Journal