11/15/09

PowerShell Find Files Script

FindFiles returns a list of files that contain the search text. The search can be plain text or a regular expression.

This function is similar to using the Select-String cmdlet with the -list switch parameter. The difference is that FindFiles supports searching across line breaks. See the examples that use the "dot matches line breaks" regex pattern (?s).
function findFiles($text)
{
begin
{
$count = 0
}
process
{
$data = [system.io.file]::readAllText($_.fullname)
if ($data -match $text) #if matches at least once...
{
$_.fullname
$count += 1
}
}
end
{
"$count files found"
}
}

Examples
#find files containing "abc"
gci c:\* -include *.txt | findFiles 'abc'

#find files containing "abc" or "xyz"
gci c:\* -include *.txt | findFiles 'abc|xyz'

#find files containing "abc", including across line breaks
gci c:\* -include *.txt | findFiles '(?s)a.*bc|ab.*c'

#find files containing "<abc>" tags, including across line breaks, and empty tags
gci c:\* -include *.txt | findfiles '(?s)<abc>.*</abc>|<abc/>'

No comments:

Post a Comment