SCAPaoT

System Center, Automation, Powershell and other Thoughts

Search for a string in a bunch of files …

A colleague had a directory with a lot of log-files in. In these he wants to search for a string and get the filename and line number automatically.

So we made this simple code in Powershell:

param($searchstring)
$items = Get-item *.log 
Foreach($item in $items)
{
                $loc = $item.fullname; 
                $content = get-content $item
                $contentcount = $content.count

                For($i = 0;$i –lt $contentcount; $i++)
                {
                               If($content[$i] –match $searchstring)
                               {
                                    "$loc:$($i+1)"
                               }
                }
}

So he was happy.

A few days later he came around with a simpler one:

select-string -path "*.log" -pattern "$searchstring" -allmatches -simplematch

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

COMMENTS