Skip to main content

NightWatchman Enterprise

Windows 1E NightWatchman Agent scripting reference

What NightWatchman power-off scripts do

NightWatchman is designed to ensure that systems are shut down or logged off in a consistent manner. This takes the onus off the user to shut down their machine and assists in desktop management, software delivery and energy saving.

Being able to shut down systems is only half the solution; the other half requires a means of saving open, edited files on the machine being shut down. In NightWatchman this task is performed by the power-off scripts.

Power-off scripts are run by NightWatchman before initiating a power-off. The purpose of the scripts is to protect unsaved data before power-off can commence by interacting with the open application windows.

  • A particular script is designed to shut down a particular process

  • The script for a process will run at least once for each running process

  • A particular script may be run multiple times if the process has multiple open documents

  • The scripts are designed to fail with an error if anything unexpected happens.

An important point to remember is that NightWatchman scripts are designed to protect data. In the event of any problems being encountered by the scripts the power down sequence will abort to prevent loss of data.

When NightWatchman begins a power-off or log-off operation, it performs the following sequence of actions for each top-most application window in each Windows session:

  1. Find the process the window is running in.

  2. Find a NightWatchman script in the NightWatchman scripts directory with the same name as the process.

  3. Run the script with CScript.exe. The window handle (HWND) of each application window will be passed on the command line to the script.

Any given process may have multiple windows open, representing different documents. The corresponding scripts will be run in turn for each window. For example, you may be editing a number of documents in Microsoft Word. In this instance, there is one process that represents Microsoft Word and one corresponding NightWatchman power-off script. The script will be run multiple times, once for each open Microsoft Word document.

Power-off script development

There are many ways of developing NightWatchman power-off scripts. We recommend one particular way that makes the process of developing a script for a particular application easier. A NightWatchman power-off script can be written in VBScript to handle the intelligent shutdown of applications, so that no data is lost when performing a user log-off.

  1. Setup the script.

    1. Find the application's process name from Task Manager. For example, the process name for Microsoft Word is WINWORD.

    2. Create a new script in the NightWatchman scripts directory with the same root name as the process. By default, the NightWatchman script directory is:

      C:\Program Files\1E\NightWatchman\Scripts

      So, depending on the type of scripting language used, the script for a process calledACMEAPPis saved in this directory as:

      ACMEAPP.vbs

      or

      ACMEAPP.js
    3. If you are creating a .vbs script, copy the contents of the ScriptTemplate.txt file (located in the Scripts folder under the NightWatchman installation directory) and paste into the new file created in step 2. Replace placeholders, for example do a global search and replace <Process Name> with ACMEAPP.

  2. Gather information for the application.

    1. Use a Windows spy utility, such as Spy++ to gather information on the application windows. These will be used in the script to access the interface for the application.

      • Determine the main application class type.

      • Find the child dialog classes.

      • Retrieve information about any message boxes that may require interaction when closing the application.

    2. Determine if there are any automation objects for the application.

    3. Check for embedded applications and other processes.

      • Find any Windows that are in different processes.

      • Determine any problems related to automation objects.

  3. General script sequence.

    The following sequence is used by all the provided NightWatchman power-off scripts – as such it is a tried and tested method for safely saving open files:

    1. Find the application window.

    2. Close all child dialogs.

    3. Run expectors to help close dialogs.

    4. Save and close documents from automation objects or Initiate a close.

    5. Use expectors to handle save messages.

    6. Save and close documents from the UI using SendKeys.

    7. Wait and check that the application window closes.

Things to keep in mind

The following points should be kept in mind when developing NightWatchman power-off scripts:

  1. NightWatchman script timeouts.

    • Will the script you are writing be fast enough to complete before the NightWatchman script timeout expires?

    • Should you extend the NightWatchman script timeout value?

  2. When multiple applications of the same type are running.

    • All the child dialogs of the applications can be closed generically.

    • Be careful that applications are not switched over during closure.

  3. Be aware of application states. You should know that applications may be in different states when the attempt at closure occurs. You need to cater for these in your scripts if you want to close successfully.

    • Which windows can be open in the application?

    • What messages are displayed in different circumstances during closure?

    • Is there anything that could interrupt the sequence you are assuming in the power-off script?

Running and testing a new power-off script

The following points give indicators of how the newly developed NightWatchman script can be tested before being placed in a production environment.

  1. Test the script from the command-line.

    Before attempting to launch the script from a NightWatchman prompted power-off, test it in a stand-alone mode from a command line. To do this, start the target application with an open test document (nothing critical, just in case the closure fails) and run the power-off script.

    Note

    The majority of the functionality in the template script relies on the fact that the script helper is installed. This takes place when the NightWatchman Agent is installed, so the script cannot be tested until this is done.

    The following shows an example command line for theacmeapp.vbsscript.

    CScript acmeapp.vbs –DEBUG=7 

    The use of the–DEBUG=7switch prompts any script based on thescripttemplat.txtfile to generate a debug log file, which is useful if the script fails to shut down the application.

  2. What if the script fails.

    Check the log file for the script. By default this is created in C:\temp as follows:

    NWM<scriptname>.log file 

    where<scriptname>is script. So the log file in our example is calledNWMACMEAPP.log

  3. Rerun the script on a locked workstation.

    After testing the script successfully from the command-line in a basic situation, re-run the script on a locked workstation. This simplest way of doing this is to add:

    Wscript.Sleep( 5000 ) 

    at the start of your power-off script. Then when running the script from the command-line, you have a reasonable amount of time to lock the workstation by hand before the main body of the script commences.

  4. Test the script in situ with a NightWatchman power-off.

    The final test is to have the new power-off script running alongside all the other NightWatchman power-off scripts. To do this, open and edit test documents in all the Microsoft Office applications and also have your target application open with an edited document. Then, trigger an immediate power-off from NightWatchman. This runs all NightWatchman power-off scripts enabling you to monitor their interaction and check for any immediate errors. If the power-off is successful, on restarting the machine, check all test documents have been saved correctly.

Write power-off scripts
Setting the script running order

In the scripting reference , we discussed the process you should go through to develop a NightWatchman power-off script. This section describes the mechanics of NightWatchman scripts and how these can be put together to implement a new power-off script.

The functionality of the NightWatchman service can be extended by creating additional power-off scripts. Administrators can write Windows scripts in VBScript to handle the intelligent shutdown of applications so that no data is lost when performing a user log-off.

During power-off, the scripts will attempt to save current versions of all open and edited files. Any open dialogs in the currently running applications are also handled in order to execute the closure of the application in a safe way. At next log-on, the user will be notified that backups have been made and given the option of accepting or rejecting these.

To run correctly, scripts must be saved in the NightWatchman scripts directory, immediately below the NightWatchman installation directory:

C:\Program Files\1E\NightWatchman\Scripts

If all the scripts are present in the root of the NightWatchman script directory, they will be run in an arbitrary order. You can control the order in which the scripts can be run, by creating specifically named subfolders in this directory and placing scripts in the sub directories.

NightWatchman supports ten sub directories named Sub0 up to Sub9. The scripts in Sub0 are run first then the ones in Sub1 and so on up to Sub9. After the scripts in the sub directories have been run, NightWatchman will then run any scripts in the main scripts directory.

Writing NightWatchman scripts

NightWatchman comes with pre-defined scripts that handle the following products: Microsoft Outlook, Microsoft Word, Microsoft PowerPoint, Microsoft Excel and Notepad. To handle other applications you can either contact 1E or write your own scripts – see Windows NightWatchman API.

How the script phase works

The power-off script phase of the NightWatchman system contains the following steps:

  • NightWatchman compiles a list of all the applications running.

  • For each application found, it searches for a script with the same base name as the application executable.

  • NightWatchman then executes this script to handle the closing of the application.

For example, a user is logged on when NightWatchman initiates a power-off, and that user has been editing a Microsoft Word document. NightWatchman first detects that Microsoft Word is running, the executable being winword.exe.

It then searches the NightWatchman scripts directory for winword.js. If it fails to find this, it will then search for winword.vbs. If it finds this script, it will then execute it to handle the closing of Microsoft Word.

Note

It is also possible to write scripts that are version specific. For example, winword.900.53.9.0.vbs

A script helper

In order to perform certain operations and to simplify the creation of application power-off scripts, the NightWatchman installation includes a script helper object called NWMScriptHelper.ocx. This is an ActiveX scripting object intended to be instantiated from within a Windows Scripting Host file. For detailed information on NightWatchman scripting see Windows NightWatchman API.

The helper object provides methods that can be called from within a script. These methods cover the following general areas:

  • To remove the delays that are sometimes explicitly added to scripts when waiting to ensure a particular window appears. Scripts can now use the helper to wait for a window to appear or disappear; see WaitForWindow and WaitWindowGone .

  • Scripts can start working on an application in an indeterminate state – the helper can Cancel, Close or OK dialogs. See CloseActiveAppDialogs .

  • The scripts can be very much more window aware when they use the helper. The helper ensures that the process being controlled contains the active window; see ActivateApp , GetAccItem , SelectAccItem and SelectSubItem .

  • The helper enables regular expressions to be used in power-off scripts for matching window names to allow more generalized matching with in the fields. See FindWindowLike .

  • The helper allows actions to be performed in response to expected events without a lot of difficult scripting. see ExpectWindow .

  • The helper supports the automatic creation of backup names. See MakeNWMFilename .

  • Other functions have been added which may be part of the WScript.Shell object or the FileScriptingObject. This will allow calls to be logged consistently.

An annotated power-off script
An annotated script for Notepad

This section provides an annotated guide for a simple script to handle Notepad.exe shutdowns. The problems dealt with are general ones, though obviously the shutdown procedures for some applications may be far more complex than the ones used for Notepad.

  1. Error checking.

    • All scripts should include an error checking section to catch errors and exit the script gracefully. As a convention, this is usually placed at the start of the power-off scripts.

      Sub ThrowError (Number, Description) 
         ObjApp = "" 
         WScript.Echo WScript.ScriptName + " " + CStr(number) + " " + description 
         NwmScript.Log WScript.ScriptName + " " + CStr(number) + " " + description 
         WScript.Quit number
      End Sub
  2. The main script body.

    • The main body of the script deals with manipulating the application in whatever state it may be in during a power-off.

  3. Initiating variables.

    • The first task is to initialize the variables used in the remainder of the script.

      hwnd = 0 '** window handle ** 
      debugx = 0
  4. Command-line arguments.

    • Two arguments are passed in by the service when the script is started – the handle to the window and a debug level parameter – this allows debugging to be enabled globally without changing the scripts.

      Set objArgs = WScript.Arguments
      For i = 0 To objArgs.Count – 1
         If objArgs = "-DEBUG" Then 
            debugx = 1 
         ElseIf UCase(Left(objArgs, 6)) = "-HWND=" Then 
            hWnd = Clng("&H" + right(objArgs, 8))
         Else 
            WScript.Echo "Usage: " + WScript.ScriptName + " [-hWnd=0xnnnnn] [-DEBUG]" 
            WSCript.Quit -2
         End If
      Next
  5. Initializing the script helper object.

    • Get the Script Helper object and initialize a few properties. Debug logging is normally off but can be turned on to help with debugging new scripts. Each call to the helper will be logged with its input parameters and the returned value. The backup directory is set to the user's profile application data area.

      '** get the NightWatchman script helper object **
      Set NwmScript = WScript.CreateObject("NWMSCRIPT.NWMScriptHelperCtrl.2") 
      NwmScript.logFileName = "c:\temp\nwmNotepad.log" 
      NwmScript.debug = debugx  '** can increase this to 3 for max logging ** 
      NwmScript.TimeoutSecs = 2 
      dumpdir = NwmScript.BackupDirectory
  6. Changing the default NightWatchman backup directory.

    • The NwmScript.BackupDirectory property returns the default location where the NightWatchman backups are saved. This is set by NightWatchman to:

      C:\documents and settings\<username>\application data\1e\NightWatchman, 

      where <username> is current user's logon name. If you want to change the save location for NightWatchman backups, change the code that sets the dumpdir variable. For example, to change the dumpdir variable to point to another location:

      dumpdir = "u:\temp"

      This example makes use of a user mapped drive u:. You can set this to any mapped drive the user may have set up on his computer. The advantage of using a user mapped drive is that they will be able to keep their NightWatchman backup files separate from all other users.

  7. Code to help with testing.

    • The following line is only used when writing/testing the scripts using "cscript.exe" . Normally hWnd is passed in by the service so there is no possibility of interacting with the wrong window.

      if hWnd = 0 Then hWnd = NwmScript.FindWindowLike ( 0, 0, "Notepad", "" )
      if hWnd = 0 Then ThrowError -1, "No Window" 
  8. getting the application process ID.

    • The NightWatchman Script Helper's ActivateApp method stores the process ID for the currently active application. This may be used subsequently to ensure that keystrokes are only sent to the application being scripted.

      NwmScript.ActivateApp ( hWnd )
  9. Closing active application dialogs.

    • Child and popup windows make it difficult for the script to continue – this function closes dialog boxes by clicking ESC, Cancel, Close or OK if that is the only option.

      NwmScript.CloseActiveAppDialogs ( "Notepad" )
  10. Getting the currently open filename.

    • For Notepad, the filename is extracted from the window caption.

      '** Get filename from window title ** 
      WndwName=NwmScript.GetWindowText ( hWnd ) 
      WScript.Echo ( WndwName ) 
      FileName = Replace( WndwName, " - Notepad", "" )
  11. Attempting to close the application.

    • Try and close the application by typing Alt-F4. If the application contains unsaved data, the popup window Do you want to save changes will appear. We cancel this for now by sending ESC.

      '** find out if it contains unsaved data ** 
      ExpectId = NwmScript.ExpectWindow("Notepad","","{ESC}","Do you want to save the changes") 
      NwmScript.SendKeys ( "%{F4}" ) '** Alt-F, 4 (Exit) ** 
      WScript.Sleep ( 1000 )
  12. Does the open file contain unsaved data.

    • ExpectCancel returns the number of times that the expected window has been seen – this is used to decide if the file contains unsaved data.

      UnSaved = NwmScript.ExpectCancel ( ExpectId )
      if UnSaved > 0 Then
  13. Handling the Save As dialog.

    • The Save As dialog box is brought up.

      NwmScript.SendKeys ( "%FA" ) '** Alt-F, A (Save As) ** 
      h = NwmScript.WaitForWindow ( 0, 0, "", "Save As" )
      if h > 0 Then 
  14. Creating a new file name.

    • The Script Helper creates a new filename using the input name as a base. The helper also makes sure that this file does not already exist as this could cause failures later. The extension and path parameters are optional but the file existence check cannot be performed without these.

      NewName = NwmScript.MakeNWMFilename ( FileName, ".txt", dumpdir ) 

      This new filename is sent to the Save As dialog.

            NwmScript.SendKeys ( "(" + dumpdir + NewName + "){WAIT_300}%S" ) 
            WScript.Echo " Saving to " + dumpdir + NewName
         end if
      end if
      
  15. Closing the application.

    • Notepad is closed.

      NwmScript.SendKeys ( "%{F4}" ) '** Alt-F, 4 (Exit) ** 
      WScript.Echo " Closing"
  16. Tidying up the environment.

    • Clean up. This section should be common to all scripts.

      WScript.Echo "Script Complete" 
      WScript.Quit 0
The NightWatchman script helper reference
Method and property categories

This section details the methods that are available in the NightWatchman NWMScriptHelper.ocx. These methods are available for use within a power-off script once an instance of the NWMScriptHelper is created. To do this, call the following code from within your script:

WScript.CreateObject("NWMSCRIPT.NWMScriptHelperCtrl.2")
Application methods

These methods provide access to currently running applications.

  • ActivateApp – activates the specified application window.

  • CloseActiveAppDialogs – closes active dialogs in the specified application.

  • CloseActiveAppDialogsLike – closes active dialogs, like the specified class, the specified application may have open, by selecting the Cancel and Close buttons.

  • GetActiveObject – creates an application object for an application with an application scripting class.

Window methods

These methods allow you to retrieve and set properties for windows open in the currently running application, refer to NightWatchman helper APIs for details.

  • ExpectWindow – waits for a window matching the specified search string or title.

  • FindInvisibleWindowLike – allows you to specify a search string to find an application window that is hidden. This is similar to the Windows API FindWindow except that it can use regular expressions for the search strings.

  • FindWindowLike – finds a window using a specified search string.

  • GetAccItem – retrieves the value of a specified item in the active window.

  • GetWindowText – gets the title of the specified window.

  • SelectAccItem – makes the specified item active.

  • SelectSubItem > – selects the specified sub item in the active window.

  • SetActiveWindow – makes the specified window active.

  • WaitForWindow – waits for the specified window to be created.

  • WaitWindowGone – waits for the specified window to close.

  • ClickButton – performs the action of the mouse clicking the specified dialog button.

  • ClickMouse – performs the action of clicking the specified mouse button.

  • SendKeys – sends keystrokes to the "Top Window" of the active application.

  • SendKeysToWindow – sends keystrokes the "Top Window" of the application containing the specified Window

  • SendKeysToDialog – sends Keystrokes to the specified window

Save file environment methods

These methods enable aspects of the applications open file environment to be utilized within the power-off script.

  • GetCmdLine – gets the command line path for the running application.

  • GetCurrDir – returns the current directory for the running application.

  • GetEnvVar – returns the value for the specified environment variable.

File methods

These methods provide file specific functionality.

  • CopyFile – copies a file to a specified location.

  • GetFullPath – gets the full path for the specified file.

  • MakeNWMFilename – creates a filename for a NightWatchman saved file.

  • MoveFile – moves a file to a specified location.

NightWatchman methods and properties

This method defines an interface for interacting with NightWatchman.

Methods
  • WriteToBackupList – outputs the name of a backed-up file to the log file so it can be viewed by the user from the NightWatchman Backup dialog.

Properties
  • PowerdownAction – this property allows you to query the power down action from within the script so that you can choose different execution paths based on the final state of the machine

Script methods and properties

The following properties and methods define settings for controlling and debugging the NightWatchman scripts.

Methods
  • Log – outputs a string to the scripts log file.

  • BackupDirectory – returns the user specific backup directory determined by NightWatchman.

    Note

    The BackupDirectory is fixed so that files backed up are saved to the logged on user's profile.

Properties

Refer to NightWatchman scripting properties for the following properties.

  • debug – specifies the level of debugging output to the log file.

  • LogFileName – sets the location of the scripts log file.

  • TimeoutSecs – sets the timeout for wait operations.

Windows NightWatchman API
NightWatchman helper APIs

Method

Description

ActivateApp

long ActivateApp(long hWnd)

Activates the specified application window. This method is similar to WScript.ActivateApp though this accepts the window handle as the input. It also stores the applications process ID for later comparisons.

Inputs
  • hWnd – window handle

Returns
  • The activated application window handle

Example

To activate the application specified by hWnd. The handle of the activated window is returned in h1 :

h1 = NwmScript.ActivateApp(hWnd);
BackupDirectory

LPCTSTR BackupDirectory()

Returns the user specific directory for NightWatchman backups. This directory is set by NightWatchman to:

C:\documents and settings\<username>\application data\1e\NightWatchman\

where <username> is the current user’s logon name. This directory is fixed by NightWatchman according to the user logged on at the time of power-off.

Inputs
  • none

Returns
  • The backup directory for the currently logged on user

Example

To return the backup directory for the current logged on user:

Dir = BackupDirectory();

ClickButton

BOOL ClickButton(long hWnd, LPCTSTR szbuttonTitle)

Performs the operation of the mouse clicking the specified dialog button by sending a BM_CLICK message to the button window.

Inputs
  • hWnd – dialog window handle

  • buttonTitle – title of button

Returns
  • Boolean – success or failure of the button-click message

Example

To simulate the mouse clicking the OK button in window h1:

NwmScript.ClickButton(h1, "OK");

ClickMouse

BOOL ClickMouse(LPCTSTR LeftOrRight)

Performs the operation of clicking the specified mouse button. This method includes code to compensate for switched mouse buttons so scripting can always assume right-handed operation. It is assumed that the cursor has already been positioned before this method is called. See SelectAccItem, SelectSubItem .

Inputs
  • LeftOrRight – mouse button L or R

Returns
  • Boolean – success or failure of the mouse-click message

Example

To position the mouse cursor on the Cancel button and click it in window h1 :

NwmScript.SelectSubItem(h1, "Cancel");
NwmScript.ClickMouse("L");

CloseActiveAppDialogs

BOOL CloseActiveAppDialogs([const VARIANT FAR& AppName]

Closes active dialogs the specified application may have open by selecting the Cancel and Close buttons. This guarantees the application is in a state ready for operations. This should be executed at the start of a script after the helper object is instantiated. The input field uses the regular expression facility for text mapping. To find the whole string ^the string$ – special characters may need to be escaped.

Inputs
  • AppName – optional application name

Returns
  • Boolean – success or failure of the close operation

Example

To close active dialogs open in Microsoft Word:

NwmScript.CloseActiveAppDialogs("Microsoft Word");

CloseActiveAppDialogsLike

BOOL CloseActiveAppDialogs([const VARIANT FAR& AppName], [const VARIANT FAR& WindowClass])

Closes active dialogs, like the specified class, the specified application may have open, by selecting the Cancel and Close buttons. This guarantees the application is in a state ready for operations. This should be executed at the start of a script after the helper object is instantiated. The input field uses the regular expression facility for text mapping. To find the whole string ^the string$ – special characters may need to be escaped. This function differs from CloseActiveAppDialogs by allowing a dialog class to be specified; applications often use their own custom dialog classes rather than the windows standard, this function is designed to cater for these exceptions.

Inputs
  • AppName – optional application name

  • WindowClass – the window class

Returns
  • Boolean – success or failure of the close operation

Example

To close active dialogs open in Microsoft Word:

CloseActiveAppDialogsLike("Microsoft Word", "#32770");
CopyFile

BOOL CopyFile(const VARIANT FAR& ExistFileName, const VARIANT FAR& NewFileName, const VARIANT FAR& Extension)

Copies a file from one location to another. The extension parameter is used as the extension might not be included in the filename due to user's Explorer settings. The method first attempts to copy the file specified. If this fails, a second attempt is made using the extension specified. If a file to be copied has zero length, CopyFile automatically deletes the copy so empty backup files are not created.

Inputs
  • ExistFileName – source filename

  • NewFileName – destination filename

  • ExtensionFile – extension

Returns
  • Boolean – success or failure of the copy file operation

Example

To copy 'guide.doc' to the c:\temp\guide.doc :

NwmScript.CopyFile("guide.doc", "c:\temp\guide.doc", ".doc")

DeactivateApp

long DeactivateApp()

Deactivates the currently selected application so that another can be selected. This is primarily required when accessing complicated applications that host embedded application windows running in another process. Deactivating the current application process and selecting another will allow you to find and manipulate windows in that process

Inputs
  • null

Returns
  • The previously activated application window handle

Example

To deactivate the application

h1 = NwmScript.DeactivateApp();

ExpectCancel

long ExpectCancel(long ExpectorId)

Cancels a call to ExpectWindow . The parameter is the ID returned from the call to ExpectWindow. The return value may be used to find out how many times the Expector action sequence was used.

Inputs
  • ExpectorId – the wait job handle to be cancelled

Returns
  • The usage count for the expector

Example

To set an ExpectWindow on a Save As dialog. The ExpectCancel call cancels the wait:

ExpectId = NwmScript.ExpectWindow("Save As", "", NewName + "{WAIT_500}%S"); 
NwmScript.ExpectCancel(ExpectId);

ExpectWindow

long ExpectWindow( const VARIANT FAR& WindowTitle, const VARIANT FAR& WindowClass, const VARIANT FAR& Action, [const VARIANT FAR& ChildTextName])

Specifies an operation to be performed on the appearance of a window specified by a search string or its title. This method may cause an exit from the WaitWindowGone method if the action specified is NULL. The operation to be performed can be cancelled using ExpectCancel . The Title and ChildText fields use the regular expression facility for text mapping. To find the whole string ^the string$, see FindWindowLike . As this call runs asynchronously, it may be necessary to put a delay into the script to give it time to detect the window.

Inputs
  • WindowTitle – the window title

  • WindowClass – the window class

  • Action – action to be performed as a sequence of keys sent by SendKeys

  • ChildTextName – optional text search string to further identify the child

Returns
  • A Job ID that can be used to cancel the expect

Example

To wait for a Save As window and type the string 'Doc1.Doc ' into the active Filename text box:

ExpectId = NwmScript.ExpectWindow("Save As", "", "Doc1.Doc")

FindInvisibleWindowLike

long FindInvisibleWindowLike(long hWnd, long hWndChild, LPCTSTR szClassLike, LPCTSTR szTitleLike)

Allows you specify a search string to find an application window that is hidden. This is similar to the Windows API FindWindow, except that it can use regular expressions for the search strings. The input fields szClassLike and szTitleLike use the regular expression facility for text mapping. To find the whole string ^the string$ – special characters may need to be escaped. This is most useful for applications that run multiple document views in a single process and share dialogs between them such as MSWord. These applications often use a hidden window to host shared child dialogs.

Inputs
  • hWnd – application window handle

  • hWndChild – child window handle

  • ClassLike – class search string

  • TitleLike – title search string

Returns
  • The application window handle if found, else 0

Example

To search for open windows with a title that starts with the text 'Visio:'

hWnd = NwmScript.FindInvisibleWindowLike(0, 0, "", "^Visio.*");

To search for the highest level dependent window of the application hWinMain and make it active. This could be used to close dependent windows before starting to close the main application.

h1 = hWinMain
while((h2 = (HWND) FindInvisibleWindowLike((long) h1, 0, "", ""))!=0)
{ h3 = h4;
  SetForegroundWindow ((long) h3);
}

FindWindowLike

long FindWindowLike(long hWnd, long hWndChild, LPCTSTR szClassLike, LPCTSTR szTitleLike)

Allows you specify a search string to find an application window. This is similar to the Windows API FindWindow, except it can use regular expressions for the search strings. The input fields szClassLike and szTitleLike use the regular expression facility for text mapping. To find the whole string ^the string$ – special characters may need to be escaped.

Inputs
  • hWnd – application window handle

  • hWndChild – child window handle

  • ClassLike – class search string

  • TitleLike – title search string

Returns
  • The application window handle if found, else 0

Example

To search for open windows with a title that starts with the text ' Visio:'

hWnd = NwmScript.FindWindowLike(0, 0, "", "^Visio.*");

To search for the highest level dependent window of application hWinMain and make it active. This could be used in closing dependent windows before starting to close the main application.

h1 = hWinMain
while((h2 = (HWND) FindWindowLike((long) h1, 0, "", ""))!=0)
{ h3 = h4;
  SetForegroundWindow ((long) h3);
}

GetAccItem

BSTR GetAccItem( long hWnd, long depth, [const VARIANT FAR& vName], [const VARIANT FAR& vRole], [const VARIANT FAR& vName2], [const VARIANT FAR& vRole2])

Retrieves the value of a specified item in an active window. The Name and Role fields are retrieved from the Windows Accessibility parameters. The depth parameter reduces the recursion depth. This should be kept as low as possible to increase the efficiency of this method.

Note

To assist with writing scripts, a third-party tool such as UI Spy, UI Verify or Spy++ can help to determine Windows Accessibility role and control names. These tools are freely available on-line.

Inputs
  • hWnd – application window handle

  • depth – recursion depth

  • vName – optional item search string 1

  • vRole – optional location for string 1

  • vName2 – optional item search string 2

  • vRole2 – optional location for string 2

Returns
  • The selected item value

Example

To search the window section of window h1, for the item label 'File name:' and return the value in it's edit box:

FileName = NwmScript.GetAccItem(h1, 3, "File name:", "window", ", "title bar");

GetActiveObject

LPDISPATCH GetActiveObject(const VARIANT FAR& vClassName)

Creates an application object. Similar to the WScript.GetObject method.

Note

This method can only be used for applications which expose an application scripting class.

Using the returned pointer will allow access to Word settings and functions directly. For example, ObjApp.Documents.Count will tell us the number of Documents that need closing.

Inputs
  • vClassName – application class

Returns
  • The application object pointer

Example

To return a pointer to the Word object application:

Set ObjApp = NwmScript.GetActiveObject("Word.Application")

GetCmdLine

BSTR GetCmdLine()

Gets the full command line path of the executing program.

Inputs
  • none

Returns
  • The full path of the command line

Example

If the following command were executed within a notepad script, CmdLine returns C:\WINNT\System32\notepad.exe

CmdLine = NwmScript.GetCmdLine();

GetCurrDir

BSTR GetCurrDir()

Returns the result of a GetCurrentDirectory in the context of the target application process. This call may return different results depending on the state of the target application. In particular, the OpenFileName and SaveAsFileName dialog boxes will set the current directory to the users default Save path.

Inputs
  • none

Returns
  • The current directory of the application process

Example

To return the current directory:

CurrentDir = GetCurrDir()

GetEnvVar

BSTR GetEnvVar(const VARIANT FAR& VarName, const VARIANT FAR& lsPath)

Gets the value of the Environment variable specified.

Inputs
  • VarName – the variable to find

  • lsPath – the application path

Returns
  • The value of the environment variable

Example

In this example, the GetEnvVar call makes sure that the SavePath is the full path name, including the drive letter.

if (DlgFileName!=FileName)
{ 
 SavePath = DlgFileName.replace(FileName,"");
  if(debug & 1) WScript.Echo("Bad SavePath : " + SavePath);
    SavePath = NwmScript.GetEnvVar("=" + SavePath.toUpperCase(), 1);
}
WScript.Echo ("SavePath : " + SavePath);
NewName = NwmScript.MakeNWMFilename(FileName, ".txt", SavePath);
GetFullPath

BSTR GetFullPath(const VARIANT FAR& vFileName, const VARIANT FAR& vDlgFileName)

Gets the full path of a specified file. This function removes the complexity of extracting the absolute pathname from the SaveAsFile dialog box. The DlgFileName would normally be extracted from the dialog using GetAccItem . This is then used in special cases where the filename was not fully resolved on the command line when the application was started.

Inputs
  • vFileName – currently unspecified

  • vDlgFileName – the filename retrieved from a Save As file box

Returns
  • The absolute path of the dialog file name

Example

The following example should resolve the following scenarios:

  • notepad c:junk.txt – has to find the current directory on C:

  • notepad \junk.txt – has to find the current drive

  • notepad junk.txt – uses the current directory

  • notepad – saves the file to the user's default Save As folder

DlgFileName = GetAccItem(h, 7, "File name:", "editable text")
Fullpath = GetFullPath(FileName, DlgFileName)

GetWindowText

BSTR GetWindowText(long hWnd)

Gets the specified window title

Inputs
  • hWnd – window handle

Returns
  • The title of the specified window

Example

To return a window's hWnd title:

WndwName = NwmScript.GetWindowText(hWnd);
Log

long Log(LPCTSTR format)

This method may be used to add data to script specific log files as defined in the property NWMScript.LogFileName. These log files are to debug scripts. Each NWM method called will log input parameters and results to this log file. The detail in this log may be made more verbose by increasing the value of the debug property. Remember to disable script specific logging before releasing scripts to production.

Inputs
  • format – the string to send to the log file

Returns
  • The number of bytes written to the log file. Returns 0 if write fails

Example

To write 'Error' to the NightWatchman error log.

NwmScript.Log("Error");
MakeNWMFilename

BSTR MakeNWMFilename(LPCTSTR szFilename, [const VARIANT & vExtension], [const VARIANT & vPath])

Adds the NightWatchman tag and current date to the passed file name or replaces it if it already exists. It then returns this new filename. The filename created is of the format filename.NWM.YYYYMMDDhhmm.ext. If this name already exists in the directory, it is written in the format filename.NWM.YYYYMMDDhhmm.A.ext with the character A being incremented until we find a non-existant filename.

Inputs
  • szFilename – the root filename

  • vExtension – optional filename extension to help ensure the extension is removed correctly

  • vPath – optional path so the new filename can be checked to make sure it does not already exist, if it does an extra character is added to the filename

Returns
  • The generated file name

Example

The NewName variable holds the returned formated filename.NWM.YYYYMMDDhhmm.ext:

NewName = NwmScript.MakeNWMFilename(thisDoc.Name, ".doc", DocPath);

http://confluence.1e.com/pages/editpage.action?pageId=47909655#

MoveFile

BOOL MoveFile(const VARIANT FAR& vExistFileName, const VARIANT FAR& vNewFileName, const VARIANT FAR& vExtension) Moves a named file to a new location.

Inputs
  • vExistFileName – source filename

  • vNewFileName – destination filename

  • vExtension – file extension

Returns

Boolean – success or failure of the move operation

Example

To move a text file from its current location to the temp directory:

NwmScript.MoveFile("guide.doc", "c:\temp\guide.doc", ".txt");

SelectAccItem

BOOL SelectAccItem(long hWnd, long depth, const VARIANT FAR& vName, const VARIANT FAR& vRole)

Makes the specified item active. The Name and Role fields are compared against the Windows Accessibility parameters. To assist with script writing, the ListAccesible(long hWnd,short depth) method is used to get the accessibility parameters for any window.

Inputs
  • hWnd – application window handle

  • depth – depth to search

  • vName – item to activate title

  • vRole – location of Item

Returns
  • Boolean – success or failure of the selection

Example

To search the window section of window h1 for the item label 'File name:' and make it active. Useful when inserting filenames in Save As boxes.

FileName = NwmScript.SelectAccItem(h1, 3, "File name:", "window", ", "title bar");

SelectSubItem

long SelectSubItem(long hWnd, LPCTSTR ControlName)

Makes an item in a window active so that subsequent mouse clicks will work.

Inputs
  • hWnd – window handle

  • ControlName – title of Item to activate

Returns
  • Handle to the sub item. Returns 0 if call fails

Example

To select the Cancel button on the activate window:

NwmScript.SelectSubItem(h1, "Cancel");

SendKeys

BOOL SendKeys(LPCTSTR Keystrokes, [const VARIANT FAR& delay])

Sends key strokes to the active application. The syntax for the Keystrokes string is similar to VB SendKeys with the addition of the {WAIT_nn}. This allows you to add a delay during the sending of a sequence of keys. The SendKeys method does a check to see if control is in the activated process before sending keys and exits if not. This method clears Caps Lock and Shift Key states at the start of each sequence. The plus sign (+), caret (^), percent sign (%), tilde (~), parentheses ( ) and braces ({}) characters have special meanings to SendKeys. To ensure that characters are not mapped, enclose the whole string within parenthesis.

For example, "(filea+b.txt)"

Inputs
  • Keystrokes – string of key strokes to send

  • delay – send delay; optional and defaults to zero

Returns
  • Always returns TRUE

Example

This will send the keys ALT, F, A

NwmScript.SendKeys("%FA");

SendKeysToWindow

BOOL SendKeysToWindow(long hWnd, LPCTSTR Keystrokes, [const VARIANT FAR& delay])

Send keystrokes to a specified window. The syntax for the Keystrokes string is the same as described in the SendKeys function.

Inputs
  • hWnd – window handle

  • Keystrokes – string of key strokes to send

  • delay – send delay; optional and defaults to zero

Returns
  • Always returns TRUE

Example

To send the keys ALT, F, A to the active dialog:

NwmScript.SendKeysToWindow(hWnd, "%FA");

SendKeysToDialog

BOOL SendKeysToDialog(LPCTSTR Keystrokes, [const VARIANT FAR& delay])

Sends key strokes to the active dialog. Sometimes the child control within a dialog may not properly pass key presses to their parent. This problem can be avoided by sending the keys to the dialog containing the focused control instead. The syntax for the Keystrokes string is the same as described in the SendKeys function.

Inputs
  • hWnd – window handle

  • Keystrokes – string of key strokes to send

  • delay – send delay; optional and defaults to zero

Returns

Always returns TRUE

Example

To send keys to the active dialog:

NwmScript.SendKeysToDialog("%FA");

SetActiveWindow

BOOL SetActiveWindow(long hWnd)

Makes the window specified active.

Inputs
  • hWnd – window handle

Returns
  • Boolean – success or failure of the activate operation

Example

To set the window specified by window handle h1, to active:

NwmScript.SetActiveWindow(h1);

WaitForWindow

long WaitForWindow (long hWndMain, long hWndUnused, LPCTSTR szClassLike, LPCTSTR szTitleLike)

Waits for the window specified to be created. scClassLike and szTitleLike can use regular expressions to match text. The script TimeoutSecs property sets the timeout length for the wait.

Inputs
  • hWndMain – window handle

  • hWndUnused – unused window handle

  • szClassLike – class search string

  • szTitleLike – title search string

Returns
  • The window handle of the created window

Example

To wait for an application's hWnd to display a Save As window:

h1 = NwmScript.WaitForWindow(hWnd, 0, ", "Save As");

WaitWindowGone

long WaitWindowGone(long hWnd, [const VARIANT FAR& vTimeout])

This method waits for the specified window to close. You can also use this method to check for "expected" windows with NULL actions. These are windows in the "expected" windows list created by the ExpectWindow method that have no action to perform. Hence acts as an Exit for this function.

Inputs
  • hWnd – window handle of window to closed

  • vTimeout – optional time out

Returns
  • Returns 0 if the window has gone within the time specified, otherwise returns the window handle given unless an expected window caused the return

Example

To wait for the window specified by window handle h1 to be gone:

NwmScript.WaitWindowGone(h1);
WriteToBackupList

BOOL WriteToBackupList(const VARIANT FAR& vFileName, const VARIANT FAR& vOrigName)

This method will log the name of a backed up file to NWMFiles.txt. The contents of this file are used for managing NightWatchman backup files through the NightWatchman System Tray icon.

Note

Use of this backup file is a requirement if you want to allow end-users to view the files backed up by NightWatchman.

Inputs
  • vFileName – newly created NightWatchman backup file

  • vOrigName – original file name

Returns
  • Boolean – success or failure of the write action

Example

To add the name of the backed-up file, DocPath + NewNm (where these variables have been set previously in the script), to the backup log along with its original name:

X = NwmScript.WriteToBackupFile(DocPath + NewNm, OrigNm);
NightWatchman scripting properties
NightWatchman scripting properties

Property

Notes

LogFileName

CString NWMScript.LogFileName – property to set the destination of the log file. Any backslash characters in the path will need to be escaped.

Inputs
  • none

Returns
  • none

Example

To set the location of the NightWatchman log file for the current script to C:\TEMP\NWM.LOG

NwmScript.LogFileName = "C:\\TEMP\\nwm.log";
PowerdownAction

integer NWMScript.PowerdownAction – property to return the action used during power down. The NightWatchman RunAlways.vbs script may be called when the computer is set to go into any of these states. This property may be used to distinguish between states where the computer is powered off and those where the computer is put into a low-power state and modify its behavior accordingly.

Inputs
  • null

Returns

This property may return one of the following values:

  • 0 – not set

  • 1 – power off

  • 2 – reboot

  • 3 – logoff

  • 4 – hibernate

  • 5 – standby

Example

To run a conditional test to see if the power down action is standby:

Set NwmScript = 
WScript.CreateObject("NWMSCRIPT.NWMScriptHelperCtrl.2") 
If NwmScript.PowerdownAction == 5 
  Then 'if powerdown action is standby 'Do SOMETHING  
  Else 'DO SOMETHING ELSE
End If

TimeoutSecs

long NWMScript.TimeoutSecs – the wait for window timeout. This property is also used as the default timeout for WaitWindowGone.

Inputs
  • none

Returns
  • none

Example

To set the timeout value to 10:

NwmScript.TimeoutSecs = 10;

debug

Short NWMScript.debug – the debugging level. The debugging level may be between 0 and 3. With 0 turning debug information off and 3 being the maximum verbose level.

Inputs
  • none

Returns
  • none

Example

To set no debug:

NwmScript.debug = 0;

To set parameter and results debugging information:

NwmScript.debug = 1;

To set the maximum amount of debugging:

NwmScript.debug = 3;