Introduction
Recently, I was needed to debug an issue in a deployed web application on production server in client premises. To get the logs on dev machine, I needed through go their approval systems and then somebody from their used to get me the logs. I cannot install other tools on production server to filter out the logs. There were too many log files to go through. So I have to live with what I have. So PowerShell came to rescue me here.
Background
PowerShell is task-based command-line shell and scripting language
built on top of the .NET Framework. So most of the basic functionality are available for our task at hand.
Using the code
So the task is parse the text file with regular expression with PowerShell commandline.
Here is the sample log file the Log4Net has generated.
2013-02-12 01:31:25 - Trying for user: 986233
2013-02-12 01:31:25 - Failed.
2013-02-12 01:31:41 - Trying for user: : 956318
2013-02-12 01:31:41 - Success.
2013-02-12 01:31:56 - Trying for user: : 468533
2013-02-12 01:31:56 - Success.
2013-02-12 01:32:11 - Trying for user: : 496924
2013-02-12 01:32:11 - Failed.
2013-02-12 01:32:26 - Trying for user: : 774469
2013-02-12 01:32:26 - Success.
2013-02-12 01:32:41 - Trying for user: : 799631
2013-02-12 01:32:41 - Success.
And now we need to write one or more command line statements to get failed user ids. Here is how I did it.
PS D:\WorkSpace\Apps> [regex]::matches((get-content .\WebLog.txt | out-string ),
'.*Trying.*\r\n.*Failed.*', "Multiline") | foreach { $_.Groups[0].Value }
And the result was as expected
2013-02-12 01:31:25 - Trying for user: 986233
2013-02-12 01:31:25 - Failed.
2013-02-12 01:32:11 - Trying for user: : 496924
2013-02-12 01:32:11 - Failed.
Points of Interest
We can get matching string easily from Select-String commandlet but It took some time for me to write multiline regular expression in PowerShell.
History
- 02/15/2013 - v1.0.0 - Initial commit.