Using WMI for Active Directory Event Notification
Many Active Directory features signal problems by writing to the Event log. It can be handy to have the domain controller notify you when this happens rather than checking the logs all the time. This notification can be built fairly simply using Windows Management Instrumentation (WMI).WMI permeates Windows Server 2003. You can discover virtually any fact about a computer, from the status of its network connections to the amount of free space on the drives to the temperature of the CPU, just by querying WMI.
WMI ReferenceA full-blown explanation of WMI falls outside the scope of this book. For a great reference, see Windows Management Instrumentation (WMI) by Matthew Lavy and Ashley Meggitt. |
[View full width]Set Events = GetObject("WinMgmts:{(Security)}").ExecNotificationQuery("select * from__InstanceCreationEvent where TargetInstance ISA 'Win32_NTLogEvent'")
Do
Set NTEvent = Events.nextevent
Notify(NTEvent.TargetInstance.Message)
Loop
Function Notify(Subject)
Set objSession = CreateObject("mapi.session")
objSession.Logon ("Microsoft Outlook Internet Settings")
Set objMessage = objSession.Outbox.Messages.Add
Set objRecipient = objMessage.Recipients.Add
objMessage.subject = "An event has occured"
objMessage.Text = Subject
objRecipient.Name = "administrator@company.com"
objRecipient.Type = 1
objRecipient.Resolve
objMessage.Send
Wscript.Echo "Message sent successfully!"
objSession.Logoff
End Function
Here are some items of interest in the script:
- The WinMgmts: entry calls the WMI interface, a COM provider.
- The (Security) entry enables the script to see changes in the Security log. (WMI demands that you announce that you'll use privileged operations, even if you are credentialed to do so already.) You can only view the Security log if you have administrator credentials, so you would need to initiate the script using RunAs if you are logged on with standard privileges.
- The ExecNotificationQuery entry submits the WMI Query Language (WQL) request to the WMI event handler. The event handler responds by creating a session for the consumer.
- The .NextEvent method tells the event handler to trigger if an event occurs.
- The Notify subroutine uses standard MAPI commands to formulate an email message.
This is just a simple example of the kind of things you can do with WMI to simplify your administrative chores. Experiment in your own environment to find ways to save time. You might even get to the point where you have a free weekend here and there