Another post in the PowerShell Box of Tricks series. Here is another script which I use to save me time and effort during my daily workload enabling me to spend more time on more important (to me) things!
Yesterday we looked at Reading Todays SQL Error Log Today we are going to search all* of the SQL Error Logs. This is usually used by DBAs to troubleshoot issues
The SQL Server Error Logs (by default) are located in the folder Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and are named as ERRORLOG.n files. The most recent has no extension the rest 1 to 6.
Using PowerShell you can easily find the location of the SQL Error Log using the ErrorLogPath Property
Image may be NSFW.
Clik here to view.
You can also read it with PowerShell using the ReadErrorLog Method. This has the following properties LogDate, Processinfo and Text. You can easily filter by any of those with a bit of PowerShell Image may be NSFW.
Clik here to view.
I have created a function which takes two parameters $SearchTerm and $SQLServer adds *’s to the Search Term to allow wildcards and searches each of the SQL Error Logs
Image may be NSFW.
Clik here to view.
Simply call it like this and use the results as needed
Image may be NSFW.
Clik here to view.
Of course, as the results are an object you can then carry on and do other things with them
Image may be NSFW.
Clik here to view.
The code can be found here
############################################################################################# # # NAME: Search-SQLErrorLog.ps1 # AUTHOR: Rob Sewell http://newsqldbawiththebeard.wordpress.com # DATE:22/07/2013 # # COMMENTS: Load function for Searching SQL Error Log and exporting and displaying to CSV # ———————————————————————— Function Search-SQLErrorLog ([string] $SearchTerm , [string] $SQLServer) { $FileName = 'c:\TEMP\SQLLogSearch.csv' $Search = '*' + $SearchTerm + '*' $server = new-object "Microsoft.SqlServer.Management.Smo.Server" $SQLServer $server.ReadErrorLog(5)| Where-Object {$_.Text -like $Search} | Select LogDate, ProcessInfo, Text |Export-Csv $FileName $server.ReadErrorLog(4)| Where-Object {$_.Text -like $Search} | Select LogDate, ProcessInfo, Text |ConvertTo-Csv |Out-File $FileName -append $server.ReadErrorLog(3)| Where-Object {$_.Text -like $Search} | Select LogDate, ProcessInfo, Text |ConvertTo-Csv |Out-File $FileName -append $server.ReadErrorLog(2)| Where-Object {$_.Text -like $Search} | Select LogDate, ProcessInfo, Text |ConvertTo-Csv |Out-File $FileName -append $server.ReadErrorLog(1)| Where-Object {$_.Text -like $Search} | Select LogDate, ProcessInfo, Text |ConvertTo-Csv |Out-File $FileName -append $server.ReadErrorLog(0)| Where-Object {$_.Text -like $Search} | Select LogDate, ProcessInfo, Text |ConvertTo-Csv |Out-File $FileName -append Invoke-Item $filename }
* Technically we are only searching the default number of 7 but if your environment is different you can easily add the lines to the function