Windows NT Systems Programming: Spring 2000

[ Home | Syllabus | Course Notes | Assignments | Search]


Windows Scripting Host

why use scripting?

what is available?

Compare to UNIX Shell Scripts


hello world

// In jscript

// HelloWorld.js
var strText1; // JScript variables have no explicit type
var strText2;
strText1 = "Hello, world!";
strText2 = "I'm the Windows Script Host.";
WScript.Echo(strText1 + "\n" + strText2);hptrd_left.gif (955 bytes)
rainbow.gif (2243 bytes)

// in vbscript

' HelloWorld.vbs
Dim strText1 ' VBScript variables have no explicit type
Dim strText2
strText1 = "Hello, world!"
strText2 = "I'm the Windows Script Host."
MsgBox strText1 & vbCrLf & strText2  hptrd_left.gif (955 bytes)
rainbow.gif (2243 bytes)

// in windows script (.ws)

<?xml version="1.0"?> hptrd_left.gif (955 bytes)
<!-- HelloWorld.ws --> hptrd_left.gif (955 bytes)
<job> hptrd_left.gif (955 bytes)
	<script language="VBScript"> hptrd_left.gif (955 bytes)
		Function MessageBox(strText)
			MsgBox strText
		End Function
	</script>
	<script language="JScript">
		var strText1;
		var strText2;
		strText1 = "Hello, world!";
		strText2 = "I'm the Windows Script Host.";
		MessageBox(strText1 + "\n" + strText2); hptrd_left.gif (955 bytes)
	</script>
</job>
rainbow.gif (2243 bytes)

Setting up and running WSH


WSH object model (Chapter 4)

Property Description
Application "This" pointer
Arguments passed on command line
FullName path to script executable
Name Descriptive name
Path path to executable
ScriptFullName  
ScriptName  
Timeout amount of time before script will be terminated
Version  
Methods  
CreateObject creates COM object form its ProgId
DisconnectObject Unload COM object
GetObject retrieves running object or creates new one
Echo  
Quit  
Sleep number of milliseconds

//Example displaying some WScript properties.

// HostInfo.js
//Displays all the information about the script file and the host engine
// ----------------------------------------------------------------------
var strHostName;
var strFrom;
var strFile;
var strScript;
strHostName = WScript.Name + " ver. " + WScript.Version + "\n";
strFrom     = "The host is: " + WScript.FullName + " running";
strFile     = WScript.ScriptName + " from " + WScript.Path + "\n";
strScript   = "Script: " + WScript.ScriptFullName;
WScript.Echo(strHostName + strFrom + strFile + strScript);

WshArgument Collection

Property Description
Item Array of command line arguments
Count Number of arguments
length same as above
// Args.js
// Demonstrates how to manage the WshArguments collection and
// display the parameters received on the command line.
//-----------------------------------------------------------------
var strArgs = "Arguments received:\n\n";
if(WScript.Arguments.length > 0) {
   for(i = 1; i <= WScript.Arguments.Length; i++)
      strArgs += i + ") " + WScript.Arguments.Item(i - 1) + "\n";
   WScript.Echo(strArgs);
} else
   WScript.Echo("No arguments specified.");

Example: Access Com object

  • Uses the "CreateObject" method of the root object.
  • Demonstrate accessing a COM object through its type library
  • Demonstrate receiving events from a COM object (events)
  • We will cover more about accessing COM later
' Events.vbs
' Navigates to a Web site and waits for some IE events.
'----------------------------------------------------------------------
Option Explicit
Dim IE
' Create the IE object
Set IE = WScript.CreateObject("InternetExplorer.Application"hptrd_left.gif (955 bytes), "Browser_") hptrd_left.gif (955 bytes)
IE.Visible = True hptrd_left.gif (955 bytes)
IE.Navigate "http://www.wrox.com" hptrd_left.gif (955 bytes)
' Loop until we close the browser...
While IE.Visible
Wend
' Here the browser is closed. Although technically unnecessary, let's tidy up
WScript.DisconnectObject IE
Set IE = Nothing
'----------------------------------------------------------------------
' Subroutines
'----------------------------------------------------------------------
Sub Browser_DownloadBegin() hptrd_left.gif (955 bytes)
   WScript.Echo "Download begins at " & Now
End Sub
Sub Browser_DownloadComplete()
   WScript.Echo "Download completed at " & Now
End Sub
Sub Browser_DocumentComplete(pDisp, URL)
   Dim doc
   Set doc = IE.Document
   WScript.Echo doc.Title
End Sub
rainbow.gif (2243 bytes)
  • ProgId (looks in registry to find this COM object and its associated IDispatch interface
  • local name (used for naming "sink" event handlers
  • Set visible property to true (so can see browser)
  • Sets URL to visit
  • This is a event function called by IE when this event happens

Jscript (aka ECMAscript)

  • see appendix B
  • c++ syntax
  • Loosely typed (string, number, boolean)
    A variable can switch types
  • Enumerator object: allows access to individual members of collections
    • newEnumeratorObject = new Enumerator(collection);
    • atEnd(): true if at end of collection
    • item(): returns current item
    • moveFirst(): sets current to be first in collection
    • moveNext(): changes current to next
  • ActiveXObject: can use instead of CreateObject
  • Array Object: dynamic sizing and other neat stuff
  • String Object:
  • Regular Expression Object: for matching

WshShell Object (chapter 4)

  • Exposes WSH shell object. (figure p. 62)
  • Properties are
    • Environment: access environment variables
    • SpecialFolders: StartMenu, SendTo, etc
  • Methods include:
    •  
    •  
    • Registry manipulation (covered later)
    • Run: an external program

 

Property Description
Environment environment variables
SpecialFolders like: favorites, startup, sendTo
Methods  
CreateShortcut  
Popup More control over information message boxes. (see pp. 64-67)
RegDelete, RegRead, RegWrite manipulates registry
Run runs external program

Running an external program

Prototype:

nRetCode = WshShell.Run(strCommand [,nWindowtype] [,bWaitOnReturn])

  • command and parameters to run
  • Windowtype: initial appearance of window (used in showwindow command in MFC)
  • Wait for spawned process to finish before continuing.

Here is a small script for starting a program (basically the Start/Run command without browsing)

// runThis.js
//Will run the program listed on the command line
// ----------------------------------------------------------------------
var strCommand;
var strStyle = 1;
var strWait = false;
switch(WScript.Arguments.length) {
	case 3:
		strWait = WScript.Arguments.Item(2);
	case 2:
		strStyle = WScript.Arguments.Item(1);
	case 1:
		strCommand = WScript.Arguments.Item(0);
		break;
	default:
		WScript.Echo("wrong number of arguments");
}
var shell = WScript.CreateObject("WScript.Shell");
var rcode = shell.Run(strCommand, strStyle, strWait);
shell.Popup("Return code is " + rcode);

  • Try this with "C:", folder name, file name with registered extension, program name, protocol

WshEnvironment Object

  • The "Environment" property is a Dictionary type (an associate memory accessed by a string key). It has the following keys
    • Process: environment variables for a process
    • System: always available
    • User: defined for the current user
    • Volatile: may not last the life of a process

// Demo program (compare VBprogram p. 98)

// EnvVars.js
// Demonstrates environmental variables
// ------------------------------------------------------------
var shell;
var env;
shell = WScript.CreateObject("WScript.Shell"); hptrd_left.gif (955 bytes)
env = shell.Environment("Volatile");
env("THISFILE") hptrd_left.gif (955 bytes)= "EnvVars.js"; // demonstrate volatile
var enumProcess = new Enumerator(shell.Environment("Process")); hptrd_left.gif (955 bytes)
shell.PopUp( "Scan the Process space without %PATH%...");
while(!enumProcess.atEnd()) { hptrd_left.gif (955 bytes)
	shell.Popup(enumProcess.item()); hptrd_left.gif (955 bytes)
	enumProcess.moveNext(); hptrd_left.gif (955 bytes)
}
// This includes %THISFILE%
shell.Popup("Scan the Volatile space...");
var enumVol = new Enumerator(shell.Environment("Volatile"));
while(!enumVol.atEnd())  {
	shell.Popup(enumVol.item());
	enumVol.moveNext();
}
rainbow.gif (2243 bytes)
  • Creates a Shell object
  • Set dictionary to associate "EnvVars.js" with key "THISFILE"
    Array index by name
  • defines an enumerator over this dictionary
  • while not at end
  • get the current item
  • then move to next item

WshShortCut Object

Three step process:

  • Step 1: CreateShortCut: creates object and sets "FullName"
  • Step 2: Set properties, e.g.
    • TargetPath: where the target resolves to
    • WorkingDirectory: directory from which to start the executable
  • Step 3: Save: saves object in location specified by FullName
Property Description
Arguments arguments for executable pointed to by shortcut
Description  
FullName path to short cut
HotKey launches short cut Ctrl+Alt+{some-key}
IconLocation path and index to icon, e.g.
C:\WINNT\System32\WScript.exe,2
TargetPath path to target of shortcut
WindowStyle see p. 80
WorkingDirectory directory where to run executable
   
Methods  
Save saves shortcut object to "FullName"
// Resolve.js
// Resolves a shortcut or creates a new one to c:\
// ------------------------------------------------------------

STR_POINTSTO = "The shortcut points to ";
STR_MISSING  = "The shortcut points to a missing file or folder: ";
STR_CREATE   = "The shortcut doesn't exist. Create one?";

YES = 6;                     // See the documentation for Popup()
BTN_YESNO = 4;               // See the documentation for Popup()

// Create the necessary objects
shell = new ActiveXObject("WScript.Shell"); hptrd_left.gif (955 bytes)
fso = new ActiveXObject("Scripting.FileSystemObject");

// Access the LNK file
lnk = shell.CreateShortcut("myShortcut.lnk"); hptrd_left.gif (955 bytes)

// Checks the target path
if(lnk.TargetPath != "") hptrd_left.gif (955 bytes)
{
   b = fso.FileExists(lnk.TargetPath); hptrd_left.gif (955 bytes)
   if(b)
      shell.Popup(STR_POINTSTO + lnk.TargetPath);     // OK, resolved
   else
   {
      // The target path isn't empty and it isn't a file. Is it a folder?
      b = fso.FolderExists(lnk.TargetPath); hptrd_left.gif (955 bytes)
      if(b)
         shell.Popup(STR_POINTSTO + lnk.TargetPath);
      else
         shell.Popup(STR_MISSING + lnk.TargetPath);
   }
}
else
{
   // Create a new shortcut? If so, make it point to c:\
   rc = shell.Popup(STR_CREATE, 0, "Shortcut", BTN_YESNO);
   if(rc == YES)
   {
      lnk.TargetPath = "c:\\"; hptrd_left.gif (955 bytes)
      lnk.Save(); hptrd_left.gif (955 bytes)
   }
}
rainbow.gif (2243 bytes)
  • Instead of CreatObject, it is faster
  • Create shortcut
  • See if already exists
  • See if file
  • or folder
  • otherwise create short cut to C drive
  • and save it

// Windows Script Host Sample Script
//
// ------------------------------------------------------------------------
//               Copyright (C) 1996-1997 Microsoft Corporation
//
// You have a royalty-free right to use, modify, reproduce and distribute
// the Sample Application Files (and/or any modified version) in any way
// you find useful, provided that you agree that Microsoft has no warranty,
// obligations or liability for any Sample Application Files.
// ------------------------------------------------------------------------


// This sample demonstrates how to use the WSHShell object to create a shortcut
// on the desktop.
var vbOKCancel = 1;
var vbInformation = 64;
var vbCancel = 2;

var L_Welcome_MsgBox_Message_Text   = "This script will create a shortcut to Notepad on your desktop.";
var L_Welcome_MsgBox_Title_Text     = "Windows Scripting Host Sample";
Welcome();

// ********************************************************************************
// *
// * Shortcut related methods.
// *

var WSHShell = WScript.CreateObject("WScript.Shell");


// Read desktop path using WshSpecialFolders object
var DesktopPath = WSHShell.SpecialFolders("Desktop");

// Create a shortcut object on the desktop
var MyShortcut = WSHShell.CreateShortcut(DesktopPath + "\\Shortcut to notepad.lnk");

// Set shortcut object properties and save it
MyShortcut.TargetPath = WSHShell.ExpandEnvironmentStrings("%windir%\\notepad.exe");
MyShortcut.WorkingDirectory = WSHShell.ExpandEnvironmentStrings("%windir%");
MyShortcut.WindowStyle = 4;
MyShortcut.IconLocation = WSHShell.ExpandEnvironmentStrings("%windir%\\notepad.exe, 0");  hptrd_left.gif (955 bytes)
MyShortcut.Save();

WScript.Echo("A shortcut to Notepad now exists on your Desktop.");

//////////////////////////////////////////////////////////////////////////////////
//
// Welcome
//
function Welcome() {
    var WSHShell = WScript.CreateObject("WScript.Shell");
    var intDoIt;

    intDoIt =  WSHShell.Popup(L_Welcome_MsgBox_Message_Text,
                              0,
                              L_Welcome_MsgBox_Title_Text,
                              vbOKCancel + vbInformation );
    if (intDoIt == vbCancel) {
        WScript.Quit();
    }
}

Scripting object (Chapter 6)

Scripting Library allows access to the Windows File System. (see figure p. 139).
Consists of the following objects:

  • Dictionary: associate array (WshEnvironment is one)
  • FileSystemObject (fso): main object allows access to:
    • Drive/Drives: single object and collection (can enumerate)
    • Folder/Folders
    • File/Files
    • TextStream: I/O control on a text file
    • Can copy/move/create/delete these objects
  • Drive: contained in a fso (see pp151-152)

 

Property Description
Drives collection of drives
Methods lots - see page 141
See p. 152 Drive Object properties
// Drives1.js
// Enumerates the drives available on a given machine
// --------------------------------------------------------
var fso, drives;
fso = new ActiveXObject("Scripting.FileSystemObject");
drives = fso.Drives;
types = new Array("Unknown", "Removable", "Local Partition",
                  "Network Share", "CD-Rom Drive", "RAM Disk"); hptrd_left.gif (955 bytes)
var e, strDrives;
e = new Enumerator(drives); hptrd_left.gif (955 bytes)
strDrives = "Drive\tType of the drive\tVolume\n\n";
for(; !e.atEnd(); e.moveNext()) hptrd_left.gif (955 bytes)
{
   var d = e.item();
   var strLabel = (d.IsReady ? d.VolumeName : "<Not Ready>");
   strDrives += d.Path + "\t" + types[d.DriveType] + "\t" + strLabel + "\n";
}
WScript.Echo(strDrives);
rainbow.gif (2243 bytes)
  • Give meaning names to drive types
  • enumerate over all drives
  • typcial enumerator loop

 

// FILE: drive.js
// AUTH: Thomas L. Fredell
// DESC: Illustrates the use of the Drive object to display information about a
//       local or network drive.
//
// Copyright 1998 Macmillan Publishing
//
var args, fso, drv;
// Retrieve arguments for the script, and check to make sure that the user
// has specified a drive letter.
args = WScript.arguments;
if (args.length != 1) {
	// User didn't specify arguments, so quit and display usage
	WScript.echo("USAGE:  drive.js  [driveletter]");
	WScript.echo("");
	WScript.echo("        Displays the information about a drive.");
	WScript.quit();
}
// Now instantiate a FileSystemObject and use it to get the Drive object
fso = WScript.CreateObject("Scripting.FileSystemObject");
drv = fso.Drives(args(0));
// Check to make sure that the drive is ready and quit if it isn't
if (!drv.isReady) {
	WScript.echo("Drive " + args(0) + " is not ready.");
	WScript.quit();
}
// The drive is ready, so we should be able to display all of the
// drive details
WScript.echo("Drive " + args(0) + " details:");
WScript.echo("");
WScript.echo("availableSpace = " + drv.availableSpace);
WScript.echo("driveLetter = " + drv.driveLetter);
WScript.echo("driveType = " + drv.driveType);
WScript.echo("fileSystem = " + drv.fileSystem);
WScript.echo("freeSpace = " + drv.freeSpace);
WScript.echo("isReady = " + drv.isReady);
WScript.echo("path = " + drv.path);
WScript.echo("rootFolder = " + drv.rootFolder);
WScript.echo("serialNumber = " + drv.serialNumber);
WScript.echo("shareName = " + drv.shareName);
WScript.echo("totalSize = " + drv.totalSize);
WScript.echo("volumeName = " + drv.volumeName);

Folders (p. 153), Files (p. 159)

 

' FolderProperties.vbs
' Provides all the information available on a given folder
' ---------------------------------------------------------

Const ReadOnly = 1
Const Hidden = 2
Const System = 4
Const Directory = 16

Dim dirName
If WScript.Arguments.Count = 0 Then
   dirName = InputBox("Enter the FULLY-QUALIFIED name of the folder:") hptrd_left.gif (955 bytes)
Else
   dirName = WScript.Arguments.Item(0)
End if

If dirName = "" Then
  WScript.Quit
End If

Set fso = CreateObject("Scripting.FileSystemObject")

' Attempt to get the folder
If Not fso.FolderExists(dirName) Then
   MsgBox "Sorry, but the folder doesn't exist!"
   WScript.Quit
End If
Set f = fso.GetFolder(dirName)

If f.IsRootFolder Then
   Set drive = fso.GetDrive(f.Drive) hptrd_left.gif (955 bytes)
   aText = Array( _
     "Folder Name:" & vbTab & fso.BuildPath(f.Path, f.Name), _hptrd_left.gif (955 bytes)
     "Short Name:" & vbTab & fso.BuildPath(f.ShortPath, f.ShortName), _
     "Type of folder:" & vbTab & f.Type, _
     "File System:" & vbTab & drive.FileSystem, _
     "Volume Name:" & vbTab & drive.VolumeName, _
     "Serial Number:" & vbTab & drive.SerialNumber, _
     "Available Space: " & vbTab & FormatNumber(drive.AvailableSpace/1024), _
     "Total Size: " & vbTab & drive.TotalSize)
Else
   aText = Array( _
     "Folder Name:" & vbTab & fso.BuildPath(f.Path, f.Name), _
     "Short Name:" & vbTab & fso.BuildPath(f.ShortPath, f.ShortName), _
     "Type of folder:" & vbTab & f.Type, _
     "Created on:" & vbTab & f.DateCreated, _
     "Accessed on:" & vbTab & f.DateLastAccessed, _
     "Modified on:" & vbTab & f.DateLastModified, _
     "Attributes: " & vbTab & FormatAttrib(f.Attributes), _
     "Total Size: " & vbTab & f.Size)
End if

MsgBox Join(aText, vbCrlf)


Function FormatAttrib(attr)
   str = ""
   If attr And ReadOnly Then str = str & "Readonly, "
   If attr And Hidden   Then str = str & "Hidden, "
   If attr And System   Then str = str & "System, "
   str = str & "Directory"
   FormatAttrib = str
End Function

Function FormatDriveType(drivetype)
   types = Array("Unknown", "Removable", "Local Partition", _
                 "Network Share", "CD-Rom Drive", "RAM Disk")
   FormatDriveType = types(drivetype)
End Function
rainbow.gif (2243 bytes)
  • Input box gets input from user (see 218)
  • we saw drive properties example earlier
  • '_' is VB continuation character

 


 

' FileProperties.vbs
' Provides all the information available on a given file
' -----------------------------------------------------------

Const ReadOnly = 1
Const Hidden = 2
Const System = 4
Const Archive = 32

' Get the name of the file to query
Dim fileName
If WScript.Arguments.Count = 0 Then
   fileName = InputBox("Enter the FULLY-QUALIFIED name of the file:")
Else
   fileName = WScript.Arguments.Item(0)
End If

If fileName = "" Then
  WScript.Quit
End If

' Create the FSO object 
Set fso = CreateObject("Scripting.FileSystemObject")

' Attempt to get the file
If Not fso.FileExists(fileName) Then
  MsgBox "Sorry, but the file doesn't exist!"
  WScript.Quit
End If
Set f = fso.GetFile(fileName)

aText = Array("File Name:" & vbTab & f.Path, _      hptrd_left.gif (955 bytes)
              "Short Name:" & vbTab & f.ShortPath, _  
              "Type of file:" & vbTab & f.Type, _
              "Created on:" & vbTab & f.DateCreated, _
              "Accessed on:" & vbTab & f.DateLastAccessed, _
              "Modified on:" & vbTab & f.DateLastModified, _ 
              "Attributes: " & vbTab & FormatAttrib(f.Attributes), _
              "Total Size: " & vbTab & f.Size) 

MsgBox Join(aText, vbCrlf) hptrd_left.gif (955 bytes)


Function FormatAttrib(attr)
   str = ""
   If attr And Archive  Then str = str & "Archive, "
   If attr And ReadOnly Then str = str & "Readonly, "
   If attr And Hidden   Then str = str & "Hidden, "
   If attr And System   Then str = str & "System, "
   str = str & "Normal"
   FormatAttrib = str
End Function
rainbow.gif (2243 bytes)
  • Create an array with all properties
  • Join makes a string out of an array of strings

Using Wild Cards

 

' filter.vbs
' Lets you query for files using wildcards
' ------------------------------------------------------------------------

' Get the name of the folder to query
Dim dirName
If WScript.Arguments.Count = 0 Then
   dirName = InputBox("Enter the FULLY-QUALIFIED name of the folder:", _
                      , dirName)
   filespec = InputBox("Enter the file specification:", , filespec)
Else
   dirName = WScript.Arguments.Item(0)
   filespec = WScript.Arguments.Item(1)
End if

If dirName = "" Or filespec = "" Then
   WScript.Quit
End If

' Get the filtered collection and dump out the filenames
Set coll = FileQuery(dirName, filespec)

If coll.Count > 0 then
   msg = ""
   For Each file In coll
      msg = msg & vbCrLf & file
   Next
   MsgBox msg
End If


Function FileQuery(dirName, filespec)

   ' Creates the required objects
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set dic = CreateObject("Scripting.Dictionary") hptrd_left.gif (955 bytes)

   ' Gets the Files collection for the folder
   If Not fso.FolderExists(dirName) Then
      Exit Function
   End If
   Set f = fso.GetFolder(dirName)
   Set files = f.Files hptrd_left.gif (955 bytes)

   ' Enumerates and processes the files
   For Each file In files
      fileName = file.Name
      If IsLike(fileName, filespec) Then
         dic.Add file.Name, file.Name hptrd_left.gif (955 bytes)
      End If
   Next

   Set FileQuery = dic
End Function

Function IsLike(strText, match)
   Dim i, str, spec, temp, token, nPos

   ' Turn strings to lower case
   str = LCase(strText)
   spec = LCase(match)

   ' Split the various components of the match string
   aInput = split(spec, "*")      ' "c*.*m" becomes Array("c", ".", "m") hptrd_left.gif (955 bytes)

   ' Walk the array of specification sub-components
   i = 0
   For Each token In aInput

      ' The first token plays an important role: the file name must begin
      '  with a substring identical to the token. hptrd_left.gif (955 bytes)
      If i = 0 Then
         temp = Left(str, Len(token))

         ' Don't match...
         If temp <> token Then
            IsLike = False
            Exit Function
         End If

         ' Removes the leading substring before next step
         str = Right(str, Len(str) - Len(token)) hptrd_left.gif (955 bytes)
      Else
         temp = str

         ' For each asterisk we come accross, we chack that what remains of
         ' the filename contains the next token of the match string.
         nPos = Instr(1, temp, token) hptrd_left.gif (955 bytes)

         ' Don't match...
         If nPos = 0 Then
            IsLike = False
            Exit Function
         End If

         ' Removes the leading substring before next step
         str = Right(str, Len(str) - nPos + 1) hptrd_left.gif (955 bytes)
      End If

      i = i + 1
   Next

   IsLike = True
End Function
rainbow.gif (2243 bytes)
  • return matching files in a dictionary
  • Get all files in this folder
  • add to dictionary object
  • split into array of strings around wild card
  • does this work for initial wild card?
  • remove already matched part of string
  • see if next token is in string
  • if so remove part mateched by wildcard

NOTE: the Shell object also can be used to manipulate folders including special folders. (p. 171)


Accessing COM objects

// Windows Script Host Sample Script
//
// ------------------------------------------------------------------------
//               Copyright (C) 1996 Microsoft Corporation
//
// You have a royalty-free right to use, modify, reproduce and distribute
// the Sample Application Files (and/or any modified version) in any way
// you find useful, provided that you agree that Microsoft has no warranty,
// obligations or liability for any Sample Application Files.
// ------------------------------------------------------------------------

// This sample will display Windows Scripting Host properties in Excel.


var vbOKCancel = 1;
var vbInformation = 64;
var vbCancel = 2;

var L_Welcome_MsgBox_Message_Text    = "This script will display Windows Scripting Host properties in Excel.";
var L_Welcome_MsgBox_Title_Text      = "Windows Scripting Host Sample";
Welcome();
    

//////////////////////////////////////////////////////////////////////////////////
//
// Excel Sample
//
var objXL = WScript.CreateObject("Excel.Application");

objXL.Visible = true;

objXL.WorkBooks.Add;

objXL.Columns(1).ColumnWidth = 20;
objXL.Columns(2).ColumnWidth = 30;
objXL.Columns(3).ColumnWidth = 40;

objXL.Cells(1, 1).Value = "Property Name";
objXL.Cells(1, 2).Value = "Value";
objXL.Cells(1, 3).Value = "Description";

objXL.Range("A1:C1").Select; hptrd_left.gif (955 bytes)
objXL.Selection.Font.Bold = true;
objXL.Selection.Interior.ColorIndex = 1;
objXL.Selection.Interior.Pattern = 1; //xlSolid
objXL.Selection.Font.ColorIndex = 2;

objXL.Columns("B:B").Select;
objXL.Selection.HorizontalAlignment = -4131; // xlLeft

var intIndex = 2;

function Show(strName, strValue, strDesc) {
    objXL.Cells(intIndex, 1).Value = strName;
    objXL.Cells(intIndex, 2).Value = strValue;
    objXL.Cells(intIndex, 3).Value = strDesc;
    intIndex++; hptrd_left.gif (955 bytes)
    objXL.Cells(intIndex, 1).Select;
}

//
// Show WScript properties
//
Show("Name",           WScript.Name,           "Application Friendly Name");
Show("Version",        WScript.Version,        "Application Version");
Show("FullName",       WScript.FullName,       "Application Context: Fully Qualified Name");
Show("Path",           WScript.Path,           "Application Context: Path Only");
Show("Interactive",    WScript.Interactive,    "State of Interactive Mode");


//
// Show command line arguments.
//
var colArgs = WScript.Arguments
Show("Arguments.Count", colArgs.length, "Number of command line arguments");

for (i = 0; i < colArgs.length; i++) {
    objXL.Cells(intIndex, 1).Value = "Arguments(" + i + ")";
    objXL.Cells(intIndex, 2).Value = colArgs(i);
    intIndex++;
    objXL.Cells(intIndex, 1).Select;
}


//////////////////////////////////////////////////////////////////////////////////
//
// Welcome
//
function Welcome() {
    var WSHShell = WScript.CreateObject("WScript.Shell");
    var intDoIt;

    intDoIt =  WSHShell.Popup(L_Welcome_MsgBox_Message_Text,
                              0,
                              L_Welcome_MsgBox_Title_Text,
                              vbOKCancel + vbInformation );
    if (intDoIt == vbCancel) {
        WScript.Quit();
    }
}
rainbow.gif (2243 bytes)
  • Set format for selected region
  • treat set of cells as an array for interating

 

// Windows Script Host Sample Script
//
// ------------------------------------------------------------------------
//               Copyright (C) 1996-1997 Microsoft Corporation
//
// You have a royalty-free right to use, modify, reproduce and distribute
// the Sample Application Files (and/or any modified version) in any way
// you find useful, provided that you agree that Microsoft has no warranty,
// obligations or liability for any Sample Application Files.
// ------------------------------------------------------------------------

// This sample demonstrates how to access Microsoft Excel using the Windows Scripting Host.

var vbOKCancel = 1;
var vbInformation = 64;
var vbCancel = 2;

var L_Welcome_MsgBox_Message_Text    = "This script demonstrates how to access Excel using the Windows Scripting Host.";
var L_Welcome_MsgBox_Title_Text      = "Windows Scripting Host Sample";
Welcome();
    
//////////////////////////////////////////////////////////////////////////////////
//
// Excel Sample
//

var objXL;

objXL = WScript.CreateObject("Excel.Application");
objXL.Workbooks.Add;
objXL.Cells(1,1).Value = 5;
objXL.Cells(1,2).Value = 10;
objXL.Cells(1,3).Value = 15
objXL.Range("A1:C1").Select;

var objXLchart = objXL.Charts.Add();
objXL.Visible = true;
objXLchart.Type = -4100;

var intRotate;
for(intRotate = 5; intRotate <= 180; intRotate += 5) {
    objXLchart.Rotation = intRotate;
}

for (intRotate = 175; intRotate >= 0; intRotate -= 5) {
    objXLchart.Rotation = intRotate;
}

//////////////////////////////////////////////////////////////////////////////////
//
// Welcome
//
function Welcome() {
    var WSHShell = WScript.CreateObject("WScript.Shell");
    var intDoIt;

    intDoIt =  WSHShell.Popup(L_Welcome_MsgBox_Message_Text,
                              0,
                              L_Welcome_MsgBox_Title_Text,
                              vbOKCancel + vbInformation );
    if (intDoIt == vbCancel) {
        WScript.Quit();
    }
}

// Windows Script Host Sample Script
//
// ------------------------------------------------------------------------
//               Copyright (C) 1996-1997 Microsoft Corporation
//
// You have a royalty-free right to use, modify, reproduce and distribute
// the Sample Application Files (and/or any modified version) in any way
// you find useful, provided that you agree that Microsoft has no warranty,
// obligations or liability for any Sample Application Files.
// ------------------------------------------------------------------------
//
// This sample demonstrates how to write/delete entries in the registry. 

var vbOKCancel = 1;
var vbInformation = 64;
var vbCancel = 2;

var L_Welcome_MsgBox_Message_Text   = "This script demonstrates how to create and delete registry keys.";
var L_Welcome_MsgBox_Title_Text     = "Windows Scripting Host Sample";
Welcome();


// ********************************************************************************
// *
// * Registry related methods.
// *

var WSHShell = WScript.CreateObject("WScript.Shell");

WSHShell.Popup("Create key HKCU\\MyRegKey with value 'Top level key'");
WSHShell.RegWrite("HKCU\\MyRegKey\\", "Top level key");

WSHShell.Popup("Create key HKCU\\MyRegKey\\Entry with value 'Second level key'");
WSHShell.RegWrite("HKCU\\MyRegKey\\Entry\\", "Second level key");

WSHShell.Popup("Set value HKCU\\MyRegKey\\Value to REG_SZ 1");
WSHShell.RegWrite("HKCU\\MyRegKey\\Value", 1);

WSHShell.Popup("Set value HKCU\\MyRegKey\\Entry to REG_DWORD 2");
WSHShell.RegWrite("HKCU\\MyRegKey\\Entry", 2, "REG_DWORD");

WSHShell.Popup("Set value HKCU\\MyRegKey\\Entry\\Value1 to REG_BINARY 3");
WSHShell.RegWrite("HKCU\\MyRegKey\\Entry\\Value1", 3, "REG_BINARY");

WSHShell.Popup("Delete value HKCU\\MyRegKey\\Entry\\Value1");
WSHShell.RegDelete("HKCU\\MyRegKey\\Entry\\Value1");

WSHShell.Popup("Delete key HKCU\\MyRegKey\\Entry");
WSHShell.RegDelete("HKCU\\MyRegKey\\Entry\\");

WSHShell.Popup("Delete key HKCU\\MyRegKey");
WSHShell.RegDelete("HKCU\\MyRegKey\\");

//////////////////////////////////////////////////////////////////////////////////
//
// Welcome
//
function Welcome() {
    var WSHShell = WScript.CreateObject("WScript.Shell");
    var intDoIt;

    intDoIt =  WSHShell.Popup(L_Welcome_MsgBox_Message_Text,
                              0,
                              L_Welcome_MsgBox_Title_Text,
                              vbOKCancel + vbInformation );
    if (intDoIt == vbCancel) {
        WScript.Quit();
    }
}


Accessing Automation objects from Chapter 25

 

// ex25a.js
// Demonstrates access to ex25a
// ------------------------------------------------------------

var ex25a, balance;

var shell = WScript.CreateObject("WScript.Shell");
ex25a = WScript.CreateObject("ex25a.Bank");

ex25a.Deposit(1000000); // deposit one million dollars
balance = ex25a.Balance();

shell.Popup("balance is " + balance);

ex25a.Withdrawal(50); // withdraw $50

balance = ex25a.Balance();

shell.Popup("balance is " + balance);

 

// ex25bauto.js
// Demonstrates access to ex25b
// ------------------------------------------------------------

var ex25b, longdata, textdata;

var shell = WScript.CreateObject("WScript.Shell");
ex25b = WScript.CreateObject("ex25b.Auto");

ex25b.LongData = 45;
ex25b.TextData = "hello";
ex25b.DisplayDialog() ;

 

// ex25c.js
// Demonstrates access to ex25c
// ------------------------------------------------------------

var clock, time;

var shell = WScript.CreateObject("WScript.Shell");
clock = WScript.CreateObject("ex25c.document");

clock.ShowWin();
shell.Popup("created clock");
clock.Time = "03:25.20";// Now();
clock.RefreshWin();
shell.Popup("set time");
clock.RefreshWin();
//Alarm = Clock.CreateAlarm(Selection.Value)
clock.CreateAlarm("7");
clock.RefreshWin();
shell.Popup("see clock");


	








Copyright chris wild 1999/2000.
For problems or questions regarding this web contact [Dr. Wild].
Last updated: April 06, 2000.