View Single Post
Old 01-11-2007   #2 (permalink)
Sung M Kim


 
 

RE: Parse Log files into a strongly type Object

"Karlos" wrote:
> The question is, how can I collect the output of the above script into
> a collection of an object for further analysis. e.g say sort on code
> and list.
> say like $x = switch -file c:\svrlog.txt -regex { .........} (which
> doesn't work.)

I have modify the script just a bit so instead of using "-file" switch for
the "switch",
the script will get content and try to match each line in a file
(I haven't tried to change the script more PowerShell like though)

# get the content of log file and match each line one by one
# each matched data will be stored in "$result"
$result = (gc .\log.txt) | % {
switch -regex ($_)
{

"^\s*(\d\d-\w\w\w-\d\d)\s*(\d\d:\d\d:\d\d\.\d\d\d)\s*(.*[0-9]\))\s*(.*)" {
$obj = New-Object -TypeName System.Management.Automation.PSObject
$prop = New-Object System.Management.Automation.PSNoteProperty
'Date', $matches[1]
$obj.PSObject.Properties.Add($prop)
$prop = New-Object System.Management.Automation.PSNoteProperty
'Time', $matches[2]
$obj.PSObject.Properties.Add($prop)
$prop = New-Object System.Management.Automation.PSNoteProperty
'Code', $matches[3]
$obj.PSObject.Properties.Add($prop)
$prop = New-Object System.Management.Automation.PSNoteProperty
'Desc', $matches[4]
$obj.PSObject.Properties.Add($prop)

$obj
}
}}
$result

# the result will display the following
# and the type of $result is "System.Object[]"
Date Time Code
Desc
---- ---- ----
----
05-Nov-06 12:00:06.287 ( -1
4360 4356)
05-Nov-06 12:00:06.287 ( -1
4360 8220)

My System SpecsSystem Spec