Wednesday, May 25, 2011

PowerShell: Search files and output results to a text file

Something I do quite often is search log files in a directory for a particular string. Notepad++ does this for me quite well, but I thought I'd see how PowerShell could do this. My first attempt started with using the .NET framework's Directory class to get all of the files in the directory, get the contents of those files with a specific file extension, search those files, and then output the results to a log file. Here is that first attempt:
$files = [System.Io.Directory]::GetFiles("C:\logfiles")
Get-Content ($files -match ".log") | findstr "someString" > log.txt
The output for this is the matching lines from the files I was searching. So, somewhat helpful but not quite what I was looking for. I want to get the file that this is coming from and if possible the line number. I did a little searching and found a different way. Here was my second attempt:
Select-String C:\logfiles\*.log -pattern "someString" > log.txt
Great! This one line gets me the name of the file, the line number, and the matching line from the file, and it runs faster. This is what I was looking for and I was about to consider this done (only took a few minutes of researching so not bad) when I was trying out a different search more along the line of what I would actually use this for - searching a directory of cpp files. The path became longer and so did the results returned which is when I found out PowerShell wraps its output. Wait...what? Seriously? PowerShell appears to wrap the output at the width of the console even when running this command from a script file. I'm not sure why and I didn't really spend a whole lot of time trying to figure out why, I just wanted it not to wrap at 120 characters. I ended up researching a few more minutes to find a different method of output and this has a width parameter. Here is the final attempt:
Select-String C:\logfiles\*.log -pattern "someString" | Out-File -filepath log.txt -width 1000
This is what I was looking for, however, Notepad++ still does this better. Because it is integrated, clicking on the search results in the Find window opens the file at the line. It was a good little experiment though and may be useful in the future.

No comments:

Post a Comment