Recently I showed how to use Get-EventLog to filter for recent eventlogs. I like this cmdlet because the output is easy to read. One drawback is that you can’t use the cmdlet to query a remote system. Right now, Get-Wmiobject is one of the few cmdlets that allows you to connect to a remote system. Which is great because we can use WMI to query for Win32_NTLogEvents. One primary challenge here is converting date time into a WMI recognized format. WMI uses timestamps in something called DMTF format that looks like 20061128160658.329710-300. PowerShell’s Get-Date cmdlet has a number of tricks it can do for manipulating and converting a datetime object. But it doesn’t have an option for converting to DMTF. However (you knew I wouldn’t bring this up if there wasn’t a solution) there is a .NET method called ToDMTFDateTime that is part of the System.Management.ManagementDateTimeConverter class. This method takes a PowerShell date-time object and converts it to DMTF.
Let’s say I want to calculate a date that is 7 days ago. Try this in PowerShell:
$d=Get-Date
$recent=[System.Management.ManagementDateTimeConverter]::ToDMTFDateTime($d.AddDays(-7))
$d
$recent
The parameter of ToDMTFDateTime is the current date minus 7 days.
I won’t go into detail about using Get-WmiObject to connect to remote computers with alternate credentials. But one thing I did find handy was limiting the properties for querying and displaying. Otherwise, the cmdlet spits out all sorts of system properties that I usually don’t care about. I found it easiest to create a query string object like this:
$query=”SelectLogFile,TimeGenerated,Type,EventCode,Message from Win32_NTLogeventwhere (type=’Error’ OR type=’Warning’) AND TimeGenerated >=’$recent'”
This is a long single line expression. I strongly recommend testing the query string in Wbemtest to make sure you get the results you are expecting. You’ll need to get a DMTF value for $recent but that’s easy enough with a Write-Host command.
The last bit of business is organizing the output for presentation. By using Select-Object and specifying the properties, I can control how data is presented.
Here’s the complete script:
$d=Get-Date
$recent=[System.Management.ManagementDateTimeConverter]::ToDMTFDateTime($d.AddDays(-7))
$computer=”dc01″
$cred=Get-Credential(“mydomain\administrator”)
$query=”Select LogFile,TimeGenerated,Type,EventCode,Message from Win32_NTLogevent where (type=’Error’ OR type=’Warning’) AND TimeGenerated >=’$recent'”
Write-Host $query
Get-WmiObject -computer $computer -credential $cred -query $query |select -property LogFile,type,TimeGenerated,EventCode,Message
Again, each expression is a single line. By separating out the query, I could turn this into a function, passing it a query string as the parameter. Actually, I’d also pass it computername and a credential object as well.
Using WMI is not as neat as using Get-EventLog, but if you need access to remote eventlogs, right now it’s the only show in town.