Search code examples
powershellsplitindexofselect-string

searching a log in powershell


I'm trying to use powershell to search a log for a particular string - and then use a particular section of a line that has that string.

The log lines I'm interested in look something like this:

2019-02-25 11:51:37.394 field1=data|field2=data|field3=data|field4=data|field5=data

I can get returns of those lines just fine - but i then need to extract the data from one of those fields to use for another search. I'm stuck there. how do i extract the data from a particular "field" (fields seperated by | and the data seperated from fieldname by =)?

$dir = "path\to\workingdir"
$file = "logfilename"
$str2 = "eventType=59"

$out = (Get-Content $dir\$file | Select-String -Pattern $str2 |out-string)

I need to extract and use the data in field 3 for another search of the log. Anything I've tried just seems to return everything that i get in $out. I can't seem to get "split" or "indexof" to work properly (at all)....though I'm not even sure if that's what i should be trying to use.


Solution

  • once you have the string with the fields in it, you can use the .Split() method to grab the items. something like this ...

    'field1=data1|field2=data2|field3=data3|field4=data4|field5=data5'.Split('|')[2].Split('=')[1]
    

    ... will give you this ...

    data3