Today I want to show you how Powershell can be used to search log files for specific strings of text and wait for updates (similarly to tail -f in the old unix world). Before the arrival of Powershell this was a pretty tedious activity involving lot of log file opening and closing. With the arrival of Powershell this task has become both easier and quicker than ever.
Let's suppose (this was my case today) that you have just joined a computer to a WSUS server and that you have some issue downloading the required patches. What you would do is to look for the Windows Update log file inside your Windows folder on your client computer.
In Powershell that's accomplished in a basic one-liner:
Get-ChildItem -Path C:\Windows *update*.log -Recurse | Get-Content -Wait | Select-String 'warning'
As you can see, I don't even know the exact name of the log file, nor the subfolder it resides in, but, with a little guessing, I can tell Powershell to look inside any subdirectory of c:\Windows for any log file contaning the word 'update' in its name, then pipe the result to Get-Content, which keeps the stream open and passes any update to the Select-String cmdlets. Select-string retrieves any line containing the 'warning' word and output it to the screen.
The result is stunning:
2013-11-20 16:01:10:783 832 160 AU # WARNING: Failed to find updates with error code 800B0001 2013-11-20 16:01:12:346 832 8b4 Misc WARNING: Digital Signatures on file C:\Windows\SoftwareDistribution\SelfUpdate\wuident.cab are not trusted: Error 0x800b0001 2013-11-20 16:01:12:346 832 8b4 Setup WARNING: SelfUpdate check failed to download package information, error = 0x800B0001 2013-11-20 16:01:12:346 832 8b4 Agent * WARNING: Skipping scan, self-update check returned 0x800B0001 2013-11-20 16:01:12:346 832 8b4 Agent * WARNING: Exit code = 0x800B0001
There I have my error! Of course, if you're less lucky, you may need to try with different log file names, or with different words in the content, but the fact is that it's anyway easier than ever before.
Note that you can replace 'warning' with a regular expression if you want to do complicated inclusion or exclusion of log messages.
For instance, to search for the keyword 'error' or 'warning' use the following regex:
Get-ChildItem -Path C:\Windows *update*.log -Recurse | Get-Content -Wait | Select-String "warning|error"
On Powershell 2.0 (which is the Powershell version of the computer I had a problem with) this can be shortened to:
gci C:\Windows *update*.log -rec | gc -Wai | Select-String "warning|error"
Not bad, isn't it? Stay tuned for more fun with Powershell.