Tuesday, December 01, 2009

PowerShell and the event log

One of the strengths of PowerShell is the easy access to WMI it provides at the command line. Before PowerShell, accessing WMI involved doing all the work from within VBScript and processing the results using the facilities available in the scripting language. PowerShell on the other hand is a built on top of the .Net framework so the manipulation of the results is far easier. I now find myself stepping away from the desktop and opening the console for a lot more tasks, I always believe that you should tell the machine what you want it to do rather than doing it yourself.

To demonstrate this the code example below will
  • Query the application event log of a remote server
  • Order the log entries by the date they occurred
  • Return the first 5 results from the set

The cmdlet Get-WmiObject is the gateway to WMI and allowed me to complete the first step with this simple command

As the results from the WMI query are stored in an array, I’m now free to manipulate the result set further using the commands available in PowerShell. Completing items two and three on my list only requires this command


The big win here is being able to run a query on a remote server but manipulate the result set on my local machine. WMI has a large set of providers which are now only a query away from my console.