powershell - Search for certain strings in a file, without looping through the content twice -
i have list of log files, these log files created every day @ 00:00:00, each day gets logged in seperate log file. 4 log files 4 different reasons created everyday, , have loop on them , select error messages.
the log files have following structure:
07.11.2016 12:00:41 flag: mandant=1, modul=v, pool=5 07.11.2016 12:00:41 verarbeiten: m1, v, pool 5, dok 526198(), doktyp 3, skript bu-co110.ff, drucker 97 07.11.2016 12:00:41 fataler fehler saldocpoolitem_process(5,): err-226/ver-dokument nicht gefunden: 0 07.11.2016 12:00:57 flag: mandant=1, modul=v, pool=5 07.11.2016 12:00:57 verarbeiten: m1, v, pool 5, dok 526198(), doktyp 3, skript bu-co110.ff, drucker 97 07.11.2016 12:00:57 fataler fehler saldocpoolitem_process(5,): err-226/ver-dokument nicht gefunden: 0 07.11.2016 12:01:13 flag: mandant=1, modul=v, pool=5 07.11.2016 12:01:13 verarbeiten: m1, v, pool 5, dok 526198(), doktyp 3, skript bu-co110.ff, drucker 97 07.11.2016 12:01:13 fataler fehler saldocpoolitem_process(5,): err-226/ver-dokument nicht gefunden: 0
as can see theres message "fataler fehler" on bottom of each block, need whole block array, , send "fataler fehler" blocks of log files in simple e-mail.
now have code, code either has mistake, or needs more 10 minutes execute, since ran 5 minutes before starting write question, , it's still not finished.
goal: have blocks in $failarray
variable
can tell me better way achieve goal? don't using get-content
twice because feel it's not necessary, i'm sure there's better solution mine:
# prepare array $failarray = @() # search log files $a = gci "c:\path" -filter *.log | ? { $_.lastwritetime -ge (get-date).adddays('-1') } # loop on log files $a | % { # there errors in log? $x = get-content $_.fullname | ? { $_ -like "*fehler*" } # if there errors in block, "time stamp" of block, 12:00:57 if ($x) { $y = $x | % { $_.split(' ')[1] } } else { return } # search whole block, depending on timestamp $z = get-content $_.fullname | ? { $_ -like "*$y*" } # add found blocks failarray $failarray += $z }
more: sometimes, first message of block has timestamp 1 second different others - possible still whole block somehow? (just nice have, not necessary)
07.11.2016 12:00:24 flag: mandant=1, modul=v, pool=5 07.11.2016 12:00:25 verarbeiten: m1, v, pool 5, dok 526198(), doktyp 3, skript bu-co110.ff, drucker 97 07.11.2016 12:00:25 fataler fehler saldocpoolitem_process(5,): err-226/ver-dokument nicht gefunden:
you can use -context
parameter , select 2 lines above match + actual match:
$failarray = gci "c:\path" -filter *.log | ? { $_.lastwritetime -ge (get-date).adddays('-1') } | % { select-string -path $_ -pattern 'fataler fehler' -context 2,0 | foreach {$_.context.precontext; $_.line} }
Comments
Post a Comment