Part 3 - Writing and Debugging MOM Scripts

By Brian Wren, Senior Consultant, Microsoft Consulting Services (Southern California)

This article is the third of a four-part series on writing scripts in Microsoft Operations Manager (MOM). The theme of the series is to compare scripts in MOM to those written for Windows Script Host in order to leverage the large amount of knowledge and materials already focused on scripts for Windows Script Host.

Part 1 - The Basics

Introduces the concepts behind MOM scripts compared to those in Windows Script Host and the common and different objects used by each. You will learn how to get output data from a script into the MOM workflow.

Part 2 - Getting Data into a Script

Focuses on getting data into a MOM script. This includes working with parameters and retrieving information from the MOM object that launches the script.

Part 3 - Writing and Debugging

Insight into the logistics of writing and debugging a script in MOM. This article covers the use of different editors and utilities for performing these functions.

Part 4 - Best Practices

Discussion of best practices and answers to general questions, such as: When should you generate an alert as opposed to an event with a MOM script? How complex should a MOM script be before you break it into multiple parts? What about security?

On This Page

Logistics of Creating a MOM Script
Editors (or lack thereof)
Saving the File
Testing and Debugging
ResponseTest
Simple Script Test
Providing Sample Objects
Creating Real MOM Objects
Debugging with ResponseTest
Preparing for Debugging
Executing a Debug Session
Active Debugging
Preparing for Active Debugging
Executing Active Debugging
ScriptContext.Echo
Conclusion

Logistics of Creating a MOM Script

In the first two parts of this series, we discussed methods of getting existing scripts to work in MOM and how to work with the MOM environment by reading and creating MOM objects through scripts. Now that we know what the scripts look like, how do we actually create them? In Windows Script Host (WSH), you pick an editor and create scripts in text files. Testing is typically as simple as running the script, getting an immediate error message, and then making corrections. This process isn’t so obvious in MOM. In this part of the series, we’ll look at the logistics of creating a script and different options for testing and troubleshooting.

Editors (or lack thereof)

Let’s start with the absolute basics - how to actually write a script. When you create a new script in MOM, after giving it a name you will be presented with a highly sophisticated editor in which you can start typing in your code. Yes, I’m being facetious. The MOM script editor really isn’t an editor - it’s a dialog box. The only thing you’re going to be able to do beyond simple typing is copying and pasting.

You might consider this lack of an editor an oversight. After all, scripts are an integral part of MOM, and we should be given a rich environment to write and test them. There never really was any intent of having script writers like us work within the dialog box. Rather, the intent is for you to use your favorite editor to create the code and then copy/paste it into the script dialog box. With the number of great editors on the market, why try to match all that functionality when so many options already exist?

So what editor should you use? You could simply use Notepad, but if you do a reasonable amount of scripting, you are absolutely going to need an editor with functionality beyond what Notepad provides. Make no doubt - scripts are just simple text files, and Notepad can be used for the most complex of them. However, it lacks key features that can make your scripting life much more pleasant, such as IntelliSense, color coding, and line numbers. These types of features can make a huge difference when working with a script longer than a few lines.

I’m not going to attempt to give you as exhaustive rundown of available editors. Anything intended to work as a Windows script editor will work great for a MOM script editor, and there are several available from a variety of vendors that will provide a host of features. The most full-featured editor provided by Microsoft is the development environment in Visual Studio .NET 2003, and this will be your best bet for the debugging process I’m going to discuss in a bit. Another editor that you probably already have without knowing it is Microsoft Script Editor, which is included with Microsoft Office 2003 (although disguised in the install under the name HTML Source Editing).

For the purposes of this article, I’m going to be using Visual Studio .NET 2003.

Saving the File

Even though you are going to end up pasting your script into MOM you are still going to want to save it to a file for testing (we’ll get to the details of that in a minute). Make sure you save your file with the same extensions that you would use in WSH: .vbs for VBScript and .js for JScript. We will be testing these scripts from a command line, and the extension identifies the language just like it does in WSH.

I wouldn’t recommend going to any great lengths to attempt to keep these script files in order or keep them synchronized with the equivalent scripts stored in MOM. The master version of any script is going to be in MOM. If you want to modify that script at a later date, you’ll most likely copy the text from MOM and paste it into your editor for modification. Rather, the text files will be where our scripts begin life before transitioning into MOM.

Testing and Debugging

So how exactly are we going to test these scripts? The general operation of MOM is actually not very conducive to this. Without any other tools, you would need to follow this basic process:

  • Create a script in MOM and paste in the code.

  • Create a rule to launch the script.

  • Deploy the rule to one or more agent computers.

  • Wait for the script to execute.

  • Look for any error events generated from a problem in your code.

  • If you get an error, GOTO 1 (couldn’t resist using a reference to good old BASIC).

Of course if your script was designed to execute in response to a particular event, you would need to generate that event in order to get the script to execute.

Wouldn’t it be cool if there was some way to quickly test a script without going through all that headache? Maybe even simulate events and performance data that the script could respond to? Heck - since we’re just dreaming, why not have a tool that would actually work with the MOM installation and create real events and performance data generated by our script in order to test related processing rules?

Dream no more - ResponseTest is your tool.

ResponseTest

ResponseTest is included with the MOM 2005 Resource Kit and is similar to the RunMOMScript utility available in the MOM 2000 Resource Kit - but better. ResponseTest works with XML to allow more complex input and output than RunMOMScript did and allows us to attach a debugger to break into executing code.

Setting up ResponseTest isn’t rocket science - just copy ResponseTest.exe into the same directory as the MOM executable files on any computer with the MOM agent. This directory will typically be C:\Progam Files\Microsoft Operations Manager 2005. We will be running the executable from a command line so plan on spending a little time in that directory.

Simple Script Test

At its most basic, ResponseTest allows us to simply pass it a MOM script in a VBS file (or JS file if that’s your preference) for execution. To illustrate this, let’s use that little Hello World script we kicked things off with in Part 1. Instead of putting the script in MOM though, let’s put it in a text file called HelloWorld.vbs. We can then execute our test with the following command line. Note that I place all my scripts in a directory named c:\scripts and use that full path on the command line.

ResponseTest /script:c:\scripts\HelloWorld.vbs

By default, ResponseTest is going to store the script results to an XML file called ResponseTestOutput.xml in the same directory with the executable. An example of our Hello World output after executing the above command line is shown here:

<ResponseResults>
  <Events>
    <Event>
      <EventTimeGenerated>7/9/2005 3:48:50 PM</EventTimeGenerated> 
      <EventID>100</EventID> 
      <EventSource>Script Test</EventSource> 
      <EventMessage>Hello world.</EventMessage> 
      <EventStrings /> 
      <EventLoggingComputer>COMOM01</EventLoggingComputer> 
      <EventLoggingComputerDomain>CONTOSO</EventLoggingComputerDomain> 
      <EventSourceComputer>CONTOSO</EventSourceComputer> 
      <EventSourceComputerDomain>CONTOSO</EventSourceComputerDomain> 
      <EventType>4</EventType> 
      <EventCategory>0</EventCategory> 
      <EventMessageDLL /> 
    </Event>
  </Events>
</ResponseResults>

As you recall, the Hello World script creates a MOM event with event ID 100 and the text “Hello world”. Even if you don’t read XML very well, you can see that we have the details of that event. In fact, we have every relevant property of the event that script would have generated if it had been executed in MOM. We just validated that our script worked as expected quickly from a command line without dealing with the complexities of MOM. If we actually wanted to use the Hello World script, we would then paste the code into a new MOM script with full confidence that it would work as expected.

But what if our script had an error? Let’s find out what happens. I’ll purposely modify the script to include an error to see how ResponseTest reacts. The script below is our old Hello World script, but I removed the event type in the call to the CreateEvent subroutine. This should produce an error.

Const EVENT_TYPE_SUCCESS = 0
Const EVENT_TYPE_ERROR   = 1
Const EVENT_TYPE_WARNING = 2
Const EVENT_TYPE_INFORMATION = 4
Const EVENT_TYPE_AUDITSUCCESS = 8
Const EVENT_TYPE_AUDITFAILURE = 16

CreateEvent 100,"Script Test","Hello world."

Sub CreateEvent(intEventNumber,intEventType,strEventSource,strEventMessage)
    Set objEvent = ScriptContext.CreateEvent()
    objEvent.EventSource = strEventSource
    objEvent.EventNumber = intEventNumber
    objEvent.EventType = intEventType 
    objEvent.Message = strEventMessage
    ScriptContext.Submit objEvent
End Sub

If you run this script with ResponseTest, you will receive some immediate output on the command line which might look a little daunting at first. If you look towards the bottom of that stream though, our relevant information shouldn’t be that difficult to pick out:

=== Status ===
HRESULT      = 0x80040202
Source       = Microsoft VBScript runtime error
Description  = Wrong number of arguments or invalid property assignment: 'Create
Event'
Resolution   =
Help File    =
Help Context = 0
Source File  =
Source Line  = 7

As we would expect, this says that our script has a missing argument on line 7 (we start at line 0). Not all that profound if you’re used to writing WSH scripts, but pretty profound for testing a MOM script. We quickly identified this error without pasting the script into MOM, waiting for it to deploy to an agent, and watching for the error event. This was a quick test with minimal effort that identified an error in our script - before we added the complexity of dropping it into MOM.

Providing Sample Objects

What about a script designed to read from the invoking object - like our Move File script in Part 2? That script is designed to retrieve information from the performance data object that invokes the script and won’t run properly without that object.

ResponseTest allows us to provide sample objects simulating the environment under which the script will be executed. This is done through the creation of a configuration file that you specify on the ResponseTest command line. The configuration file is an XML file containing all of the relevant information about the MOM environment that you want to simulate for execution of the script - including all the details of any invoking objects. You can actually place the entire text of the script in the configuration file itself, but I find it easier to manage the script in a separate file. You will probably be modifying the script, and keeping it separate allows execution with different configuration files as required.

In the case of our Move File script, we need to supply a performance data object that the script will read from as well as a script parameter named ArchiveLocation, which provides the path to the archive location. We can get the required formatting for the configuration file from the ResponseTest Readme. For the details of our performance data object, let’s execute our Get File Size script using ResponseTest in order to generate the performance data in XML format. The output will look like this:

<ResponseResults>
  <PerfObjects>
    <PerfData>
      <PerfObject>File</PerfObject> 
      <PerfCounter>File Size</PerfCounter> 
      <PerfInstance> C:\Logs\applog.txt</PerfInstance> 
      <PerfTime>7/29/2005 7:48:33 AM</PerfTime> 
      <PerfValue>103463316.</PerfValue> 
      <PerfComputer>COMOM01</PerfComputer> 
      <PerfDomain>CONTOSO</PerfDomain> 
    </PerfData>
  </PerfObjects>ol.</ResponseResults>

Using this output and the formatting defined in the Readme, we can create the following configuration file for the purposes of driving our Move File script:

<ConfigData>
  <PerfData>
    <PerfObject>File</PerfObject> 
    <PerfCounter>File Size</PerfCounter> 
    <PerfInstance> C:\Logs\applog.txt</PerfInstance> 
    <PerfTime>7/29/2005 7:48:33 AM</PerfTime> 
    <PerfValue>103463316.</PerfValue> 
    <PerfComputer>COMOM01</PerfComputer> 
    <PerfDomain>CONTOSO</PerfDomain> 
  </PerfData>
  <Script>
    <ScriptParams>
      <ScriptParam Name="ArchivePath">c:\archive\</ScriptParam>
    </ScriptParams>
  </Script>
</ConfigData>

The PerfData node provides the details of the performance data object that we’re simulating. To test objects with different details, we can just change them in the configuration file and rerun ResponseTest with the changes. Obviously, if my script were meant to run from an event or alert, I could provide those objects instead of the PerfData object.

The Script node allows us to provide information about the script itself. In this case, all we need to define is a single script parameter.

There are several other pieces of information we could add to the configuration file, but this is the minimum we need to provide to our script. Other possible information is documented in the Readme file and sample configuration files that come with ResponseTest; I’ll let you have a look at those on your own.

To specify the Config file and the script file when running ResponseTest, run a command line similar to the following:

ResponseTest /script:c:\scripts\MoveFile.vbs /config:c:\scripts\MoveFile_Config.xml

When the test is executed, we should get the resulting event in the ResponseTestOutput.xml file, and our file should be moved. In fact, if the file specified in the simulated PerfData object is not present on the computer executing the script, we are going to get an error similar to the one we saw in the above example with Hello World.

Important: ResponseTest executes the script. While any MOM objects that the script would create are simulated, all the other actions taken by the script actually occur. So in our Move File test, the file really is moved.

Creating Real MOM Objects

Under default operation, scripts run in ResponseTest won’t create anything in MOM. Any events, performance data, or alerts created by the script will exist only within the context of the XML output. This functionality is usually what you want because you want to test your script without mucking with your MOM environment. This gives you the ability to inspect the details of any objects that would get created before you let your script go out and create them.

There are times, though, when it would be helpful to have those objects actually get created. For example, maybe you have a rule or two in MOM looking for the output from your script. It would be helpful if we could create the test objects and watch those rules fire.

ResponseTest makes this easy by providing a command line switch to specify the Run Mode. The default Run Mode is Emulation, which just simulates created objects in the output file, but if we change the Run Mode to MOM then those objects will be created in MOM.

Our Get File Size and Move File script combination also provides a good example of how you might use MOM Run Mode. The Move File script might already be in place in your MOM environment along with a rule ready to execute it in response to a piece of performance data at a particular threshold. Our Get File Size script will create that piece of data. If we create that data in MOM, we can watch the response of those rules in addition to correcting operation of the script.

To set the Run Mode, use a command line like the following:

ResponseTest /script:c:\scripts\GetFileSize.vbs /runmode:mom

Debugging with ResponseTest

Simply executing your script with ResponseTest is going to help a lot in your testing and should quickly become an integral part of your regular development process. You should be able to identify and correct most problems with the simple processes we just went through. But what if the problem isn’t so easy to locate? Wouldn’t it be interesting if we could perform a full debug scenario like Visual Studio .NET developers do? Actually, we can.

Simply add the /x argument to the ResponseTest command line, and the tool will pause before executing the script. This will allow us to start Visual Studio .NET 2003 and use it to walk through the script line by line, inspecting variables and debugging problems along the way.

Preparing for Debugging

You will be able to perform debugging on an agent computer if Visual Studio .NET is installed locally on that computer. A common scenario though is having Visual Studio .NET running on your workstation and debugging a script running on another computer with the MOM agent. In that case, the agent computer running the scripts needs to have Remote Debugging Components installed. Without this, Visual Studio .NET has nothing to attach to for the debugging session.

Because of this requirement, you probably aren’t going to perform debugging against a production server. Rather, you might install these components on a test or lab server in order to perform this process.

Remote Debugging Components are installed from the Visual Studio .NET 2003 installation CD. The MOM 2005 SDK describes the installation process, which is actually quite simple: select Remote Components Setup from the main installation menu then scroll down to the Install Full button.

Executing a Debug Session

There is a slight quirk to be aware of when using /x to debug with ResponseTest. ResponseTest doesn’t actually start the debug engine until you press a key at the prompt initiating the script execution. Of course, the script will then execute to completion before you can get your debugger into place, so you need to attach Visual Studio .NET before letting the script execute. For that reason, you are going to see an error message saying that no script is running when you try to attach the Visual Studio .NET debugger. You can ignore that error because the debugger will still be in place waiting for the script to start.

Use the following process to initiate a debug session:

  • Start ResponseTest with /x on the command line.

  • Start Visual Studio .NET 2003 (either on the local computer or on another if Remote Debugging Components are installed on the ResponseTest computer).

  • From Visual Studio .NET, select Tools | Debug Processes.

  • Select the computer that ResponseTest is running on (the default will be the local computer) and click Refresh. You should get a list of processes running on that computer.

  • Select the ResponseTest process in Available Processes and click on Attach.

  • Select Script and click OK.

  • In Debugged Processes, click Break. This is where you will receive that error message about no script running - ignore it.

  • Go back to ResponseTest and press a key to start the script.

If you did everything correctly, Visual Studio .NET will catch the script on the first line allowing you to perform a debug session. Providing the details of how to operate the debug features of Visual Studio .NET is beyond the scope of this article, but I would like to point out some of the major concepts at least. If you already have some development experience, this shouldn’t be anything you don’t already know. If the extent of your development life is writing a few WSH scripts, then this should get you started in doing some simple - but valuable - debugging.

Breakpoints

A breakpoint is a line in your code where you want execution to pause. The script will execute to the breakpoint and then stop, allowing you to inspect variables and methodically step through the code looking for any errors along the way. When you debug a MOM script, execution of the script automatically breaks on the first line. You then have the option of slowly walking through the code (using the commands described below) or setting an additional breakpoint later on and launching execution to that point. You set an additional breakpoint in Visual Studio .NET by clicking to the left of the line where you want to break.

Breakpoint

Figure 1 - Move File script at a breakpoint on first line

Stepping through code

The entire point of breaking into a script is to be able to step through it line by line in order to validate proper operation. The current line (which is the line about to be executed) will be highlighted, and you can control the execution of the script from the Debug toolbar.

Debug Toolbar

Figure 2 - Debug Toolbar

Table 1 lists the most common commands from the debug toolbar that you are going to use. These allow you to methodically control the execution of the script while you inspect the values of variables and ensure proper operation of the script.

Table 1 - Debug execution commands

Command

Description

Step IntoStep Into

Executes the current line of code and then breaks at the next line - even if that next line is in a subroutine or function.

Step OverStep Over

Similar to Step Into except that if the next line calls a subroutine or function, that entire procedure will be executed before the break occurs at the next line of the script.

RunRun

Commences execution of the script from the current line. Script will either run to completion or stop at the next breakpoint.

StopStop

Stops the script without executing the current line and ends the debug session.

Inspecting Variables

The most valuable information you are going to get during a debug session is typically the value of variables in the script. With the script paused, you can check the current value of any variable whose value was set in preceding lines of code. You can either position the mouse over the variable name to get a tooltip with the current value, or you can refer to the local variables window. This window will list the current value of all variables defined to the current execution point of the script.

Figure 3 shows the local variables window during execution of the Move File script. You can see from this illustration that we can quickly check critical values that the script is using. For example, if the script was getting an error that the file we are trying to move doesn’t exist, we could quickly determine the exact value being used for the strFilePath variable.

Local Variables

Figure 3 - Local variables window

Active Debugging

What happens if you use all of your due diligence with ResponseTest but still encounter some problem with the script running in your actual MOM environment? There are differences in running with ResponseTest versus running in MOM, such as the security context under which the script is run. When you run a script in ResponseTest it will be running under the security context of the currently logged on user. Scripts in MOM run in the MOMHost process under the credentials of the MOM Action Account. This is just one example of the different variables that may come into play between a script running in ResponseTest and a script running in MOM. We will catch almost all script errors with ResponseTest, but there can be some frustrating ones that slip through.

We have the ability to do the same type of debugging we did with ResponseTest against an actual script running in the MOMHost process on an agent computer. This is typically a last resort, since it requires installing Remote Debugging Components or Visual Studio .NET on the agent computer as we described above. While this is a safe installation, I’m certainly not going to recommend that you install this extra component on a production server. Rather, this is a process that should be performed on a test server or in a lab and reserved for those cases where you simply cannot identify a problem with a script through other means.

Preparing for Active Debugging

Preparing for Active Debugging is a little more involved than preparing for debugging with ResponseTest, as you can see from the following steps.

Install Remote Debugging Components

This is identical to the procedure described above for debugging with ResponseTest. You will either need Visual Studio .NET installed locally on the computer running the script, or you will need Remote Debugging Components installed.

Enable Active Debugging in MOM

To instruct MOM to initialize the debug engine, you must enable active debugging in the registry. This is done by setting the registry key HKLM\SOFTWARE\Mission Critical Software\OnePoint\EnableActiveDebugging to 1. Once the key is set, you must restart the MOM service.

Note: If you’re wondering why this value is under a key called Missions Critical Software rather than something like Microsoft\MOM, you’re looking at a bit of MOM history. MOM started its life as a product called OnePoint Operations from Mission Critical Software.

Specify Scripts to Debug

When you attach your debugger to MOM (which we’re going to do in a moment), the next script that executes will be captured by the debugger with a break on the first line of code. This can be difficult since the next script that executes may not be the one you want. Remember, there are typically various scripts that may be waiting to execute on a MOM agent, and one may fire before the one that you’re trying to test. Fortunately, we can specify the script (or scripts) that you are interested in.

The registry value to specify the scripts that are allowed to be debugged is HKLM\SOFTWARE\Mission Critical Software\OnePoint\DebugEnabledScripts. The default for this value is * which is a wildcard specifying all scripts - probably not what we want. You can modify this value to the name of a specific script to be debugged, a list of script names separated with commas, or a more specific string containing a wildcard. With this in place, any script may execute on the MOM agent, but the debugger will catch the script only if it matches one of the values in the registry key.

Executing Active Debugging

The basic idea to active debugging is waiting for a script to execute in MOM and then catching it with the debugging application. You can then control the execution of the script following the same debugging procedures we went through with ResponseTest. The script is actually executing on the agent computer as it would normally, but your debugger retains control and provides insight into the script as it executes.

In order to perform Active Debugging, use the following procedure:

  • Start Visual Studio .NET 2003 (either on the local computer or on another if Remote Debugging Components are installed on the ResponseTest computer).

  • From Visual Studio .NET, select Tools | Debug Processes.

  • Select the computer that the script will be running on and click Refresh. You should get a list of processes running on that computer.

  • Select the MOMHost process in Available Processes and click on Attach.

  • Select Script and click OK.

  • In Debugged Processes, click Break.

  • Wait for your script to execute, at which point it will break on the first line, and you can begin your debugging.

Once the debug session starts, the concepts are the same as those described above for ResponseTest.

ScriptContext.Echo

I introduced you to ScriptContext.Echo back in Part 1 of this series and promised you that I would provide the details for using this command for testing and debugging. Now is the time to make good on that promise.

As we described in Part 1, ScriptContext.Echo is useful for quick and dirty debugging of a script by launching it from a Task. Any ScriptContext.Echo commands will be delivered through the event generated by the Task. This can be used for a quick test to view output or the value of a certain variable.

ScriptContext.Echo has another interesting behavior though. In addition to outputting to a Task status event, it also has the ability to send output to a debug file whenever the script is executed. In this case, it doesn’t matter what invoked the script.

Unlike active debugging, you don’t need any components on the server to create a debug file; you simply need to enable active debugging through the same registry setting I showed you above and restart the MOM service. Once this is done, any ScriptContext.Echo command in a script specified for debugging will be written to a file named AgentResponses-<Management Group Name>.log in the directory %windir%\Temp\Microsoft Operations Manager.

Since ScriptContext.Echo has no effect when debugging is not on, you can sprinkle the command throughout scripts running in production in order to return the values of critical variables. If you have some problems with a script, you can essentially put an agent into “debug mode” by simply enabling active debugging. Any ScriptContext.Echo commands in any scripts running on that agent will immediately become active and will write to the debug file on the agent computer. You can quickly access this information to determine if the script is running properly or where there might be a problem. When you have the information you need, turn debugging off by changing the registry value back to 0.

As an exercise, let’s add some ScriptContext.Echo commands to the Move File script that we’ve been using for our debugging examples. Here’s the original version:

Const EVENT_TYPE_SUCCESS = 0
Const EVENT_TYPE_ERROR   = 1
Const EVENT_TYPE_WARNING = 2
Const EVENT_TYPE_INFORMATION = 4
Const EVENT_TYPE_AUDITSUCCESS = 8
Const EVENT_TYPE_AUDITFAILURE = 16

If ScriptContext.IsPerfData = False Then
        CreateEvent 200, EVENT_TYPE_ERROR, "Scripting MOM", "The script " & _
        ScriptContext.Name & " may only be executed in response to a performance rule. "
Else
        Set objPerfData = ScriptContext.PerfData
        strFilePath = objPerfData.InstanceName
        strArchivePath = ScriptContext.Parameters.Get("ArchivePath")

        Set objFSO = CreateObject("Scripting.FileSystemObject")
        objFSO.MoveFile strFilePath , strArchivePath
End If

Sub CreateEvent(intEventNumber,intEventType,strEventSource,strEventMessage)
        Set objEvent = ScriptContext.CreateEvent()
        objEvent.EventNumber = intEventNumber
        objEvent.EventType = intEventType 
        objEvent.EventSource = strEventSource
        objEvent.Message = strEventMessage
        ScriptContext.Submit objEvent
End Sub

We can prepare that script with a few ScriptContext.Echo statements so that we can get some useful information if the agent is put into debug mode. The modified version is shown here:

Const EVENT_TYPE_SUCCESS = 0
Const EVENT_TYPE_ERROR   = 1
Const EVENT_TYPE_WARNING = 2
Const EVENT_TYPE_INFORMATION = 4
Const EVENT_TYPE_AUDITSUCCESS = 8
Const EVENT_TYPE_AUDITFAILURE = 16

ScriptContext.Echo "IsPerfData: " & ScriptContext.IsPerfData
If ScriptContext.IsPerfData = False Then
        CreateEvent 200, EVENT_TYPE_ERROR, "Scripting MOM", "The script " & _
        ScriptContext.Name & " may only be executed in response to a performance rule. "
Else
        Set objPerfData = ScriptContext.PerfData

        strFilePath = objPerfData.InstanceName
        ScriptContext.Echo "File path: " & strFilePath
        strArchivePath = ScriptContext.Parameters.Get("ArchivePath")
        ScriptContext.Echo "Archive path: " & strArchivePath

        Set objFSO = CreateObject("Scripting.FileSystemObject")
        objFSO.MoveFile strFilePath , strArchivePath
        ScriptContext.Echo "Completed file copy."
End If

Sub CreateEvent(intEventNumber,intEventType,strEventSource,strEventMessage)
        Set objEvent = ScriptContext.CreateEvent()
        objEvent.EventNumber = intEventNumber
        objEvent.EventType = intEventType 
        objEvent.EventSource = strEventSource
        objEvent.Message = strEventMessage
        ScriptContext.Submit objEvent
End Sub

This shouldn’t appear to be all that profound. I simply put a ScriptContext.Echo command identifying critical points in the script and where an important variable was calculated. Put an agent into debug mode, and we get this useful information written into the debug file - an excerpt of which is shown here:

--- RESPONSE: 'script: TechNet: Scripting MOM: Move File' succeeded.  
STARTTIME: 7/29/2005 17:24:26 ENDTIME: 7/29/2005 17:24:26
--- Output --- 
IsPerfData: True
File path: C:\Logs\applog.txt
Archive path: C:\Archive\
Completed file copy.
--- /Output ---

Conclusion

At this point in the series, you should be confident that you can efficiently write and test a MOM script. We have a tool to validate that the script operates correctly before we put it into MOM and methods to debug problems that find their way through.

The first three parts of this series have provided information on the possibilities of MOM scripts and the different options and tools at your disposal. The final article will focus on best practices. Rather than discussing all the possibilities of what you can do, we will focus on recommendations for what you should do.