Reading Event Logs (Part 4)

by Dec 14, 2020

In the previous tip we encouraged you to deprecate the Get-EventLog cmdlet and instead start using Get-WinEvent – because the latter is more powerful, and because the former is no longer supported in PowerShell 7.

Querying events via Get-WinEvent requires a hash table as you have seen in the previous examples. The following command, for example, returns a list of installed updates:

Get-WinEvent -FilterHashtable @{
  LogName = 'System'
  ProviderName = 'Microsoft-Windows-WindowsUpdateClient'
  Id = 19
  }

In reality, event data is always stored using the XML format, and all queries use XPath filter queries to retrieve the data for you. If you were an XML and XPath guru, you could have directly issued this command to get the same result:

Get-WinEvent -FilterXML @'
<QueryList><Query Id="0" Path="system"><Select Path="system">*[System/Provider[@Name='microsoft-windows-windowsupdateclient'] and (System/EventID=19)]</Select></Query></QueryList>
'@

The hash table serves as a handy shortcut. Internally, the information contained in the hash table is translated to the XML statement above. Fortunately, it is not hard at all to transform hash tables to XML because Get-WinEvent does it for you: simply submit a hash table, and ask to get back the XML statement:

$result = Get-WinEvent -FilterHashtable @{
  LogName = 'System'
  ProviderName = 'Microsoft-Windows-WindowsUpdateClient'
  Id = 19
  } -MaxEvents 1 -Verbose  4>&1

$result | Where-Object { $_ -is [System.Management.Automation.VerboseRecord] }

In essence, by submitting the -Verbose parameter, you ask Get-WinEvent to return the calculated XML statement to you. By redirecting the channel 4 to the output channel 1, you can capture the verbose messages to $result and filter for verbose messages. This way, you can capture the calculated XML:

 
VERBOSE: Found matching provider: Microsoft-Windows-WindowsUpdateClient
VERBOSE: The Microsoft-Windows-WindowsUpdateClient provider writes events to the System log.
VERBOSE: The Microsoft-Windows-WindowsUpdateClient provider writes events to the Microsoft-Windows-WindowsUpdateClient/Operational log.
VERBOSE: Constructed structured query:
VERBOSE: <QueryList><Query Id="0" Path="system"><Select Path="system">*[System/Provider[@Name='microsoft-windows-windowsupdateclient'] and 
VERBOSE: (System/EventID=19)]</Select></Query></QueryList>. 
 


Twitter This Tip! ReTweet this Tip!