WMI events

You can also register for events coming from WMI classes or by using WQL queries. WMI stands for Windows Management Instrumentation and can be used for various OS automation purposes. Many cmdlets use WMI/CIM internally. As an operations or development person, you, for example, want to watch for modifications to the Windows service you deployed. With a WMI watcher, this can be achieved rather elegantly.

Moving on to the Common Information Model (CIM), the same learning applies to the Register-CimIndicationEvent cmdlet to register for CIM events not only on Windows, but also on, for example, Linux operating systems.

For more information on WQL, the WMI Query Language, see: https://msdn.microsoft.com/en-us/library/aa394606(v=vs.85).aspx. WQL provides a SQL-like syntax to query data sets from WMI/CIM providers.
$actionScript = {
# Your previous service configuration
$serviceBefore = $eventargs.NewEvent.PreviousInstance

# Your modified service configuration
$serviceAfter = if($eventargs.NewEvent.TargetInstance)
{
$eventargs.NewEvent.TargetInstance
}
else
{
$eventargs.NewEvent.SourceInstance
}

Compare-Object $serviceBefore $serviceAfter -Property Name,Description,StartMode | Out-Host
}

# No additional .NET here - we monitor for any changes of a service
# Changes are InstanceModificationEvents, while our instance is a Win32_Service
# Here we also use a SourceIdentifier as a friendly name for our event
Register-WmiEvent -Query "SELECT * FROM __instanceModificationEvent WITHIN 5 WHERE targetInstance ISA 'win32_Service'" `
-SourceIdentifier ServiceModified -Action $actionScript

# When finished
Unregister-Event -SourceIdentifier ServiceModified

# Same, but different...
Register-CimIndicationEvent -Query "SELECT * FROM CIM_InstModification WITHIN 5 WHERE targetInstance ISA 'WIN32_Service'" `
-SourceIdentifier CimServiceModified -Action $actionScript

# When finished
Unregister-Event -SourceIdentifier CimServiceModified

Both WMIEvent as well as CimIndicationEvent will use the same action script block to react to a service change in the preceding example. From our event arguments, we can this time we can examine the target instance (that is, the target instance of a WMI/CIM class). Because of our instance modification event, we also get the previous instance—how cool is that?

With very few lines of code, we have now subscribed to WMI/CIM events and can react to them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset