# ==================================================================================================== # # NAME: Get-WMIEvent.ps1 # # AUTHOR: Yan Pan # DATE : 10/15/2007 # # COMMENT: This function accepts a WQL query, a namespace and an array of property names. # Based on the given parameters, the function creates a watcher to # monitor the events retrieved by the WQL query under the namespace. # This function allows its execution to be stopped by pressing the Esc key. # ===================================================================================================== function Get-WMIEvent([string] $wqlQuery, [string] $namespace, [string[]] $properties) { $ESCkey = 27 # 27 is the key number for the Esc button. $objWql = New-Object System.Management.WqlEventQuery $wqlQuery $objScope = New-Object System.Management.ManagementScope $namespace $objWatcher = New-Object System.Management.ManagementEventWatcher $objScope, $objWql $options = New-Object System.Management.EventWatcherOptions $timespan = New-Object System.TimeSpan(0, 0, 10) # Default interval is set to 10 seconds $options.TimeOut = $timespan $objWatcher.Options = $Options $objWatcher.Start() while ($true) { trap [System.Management.ManagementException] {continue} $objEvent=$objWatcher.WaitForNextEvent() if ($objEvent) { $objEvent | Select-Object $properties Clear-Variable -name objEvent } # Press Esc to stop the watcher and exit this function if ($host.ui.RawUi.KeyAvailable) { $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp") if ($key.VirtualKeyCode -eq $ESCkey) { $objWatcher.Stop() break } } } }