Databases Reference
In-Depth Information
if ($host.ui.RawUi.KeyAvailable) {
$key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp")
# If the Esc key is pressed, unregister the event subscription, break the loop,
and exit this function.
if ($key.VirtualKeyCode -eq $ESCkey) {
Unregister-Event "sqlevents"
break
}
}
To retrieve different events, you only need to change the particular WQL query, the namespace, and
the selected properties of the events. Therefore, it makes sense to encapsulate the preceding steps in
a function, and reuse the function to monitor different events throughout this chapter. The complete
function Get-WMIEvent.ps1 is shown here:
function Get-WMIEvent([string] $eventQuery, [string] $namespace, [string[]]
$properties)
{
$ESCkey = 27 # 27 is the key number for the Esc button.
# If an event subscription called "sqlevents" already exists, unregister it first.
if (Get-EventSubscriber 'sqlevents' -ErrorAction SilentlyContinue) {
Unregister-Event "sqlevents"
}
# Create an event subscription called "sqlevents" that registers to the events
specified by the $eventQuery under the $namespace.
Register-WmiEvent -Namespace $namespace -Query $eventQuery -SourceIdentifier
"sqlevents"
while ($true) {
# Get new events
$objEvents = Get-Event -SourceIdentifier "sqlevents" -ErrorAction
SilentlyContinue
# If new events arrive, then retrieve the event information.
if ($objEvents) {
# Loop through the collection of new events
for ($i = 0; $i -lt $objEvents.Count; $i ++ ){
$objEvents[$i].SourceEventArgs.NewEvent | Select-Object
$properties
# Remove the event after its information has been processed.
Remove-Event -EventIdentifier $objEvents[$i].EventIdentifier -
ErrorAction SilentlyContinue
}
}
# Check if the Esc key is pressed
if ($host.ui.RawUi.KeyAvailable) {
$key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp")
Search WWH ::




Custom Search