You're on the right path, Select-String is the Cmdlet for the task. Wrapping the Select-String statement in parenthesis collects all objects before passing them on to ForEach-Object, this affects performance, specially when processing large files/collections. Optionally, you can initialize $Sum in FoEach-Object's -Begin ScriptBlock and output it in ForEach-Object's -End ScriptBlock.
Using a couple of ,Net methods -IO.File's ReadAllText and Regex's Matches- can speed up the process dramatically but your RAM will suffer, but you can cleanup with another .Net method, GC's Collect. You could write up a function to make it simpler.
# both one-liners, look out for word wrapping...
# pure PowerShell
Select-String -AllMatches foo .\foobarbaz.txt | % {$sum = 0} {$sum += $_.Matches.count} {$sum}
# .Net through PowerShell, note the fullpath of the file
[regex]::Matches([IO.File]::ReadAllText('c:\somedir\foobarbaz.txt'), 'foo', 'IgnoreCase').count; [gc]::Collect()
IO.File's ReadAllText Method is fast. More about it here:
http://msdn.microsoft.com/en-us/libr...adalltext.aspx
Regex's Matches Method is casesensitive, use the IgnoreCase option. More here:
http://msdn.microsoft.com/en-us/libr...x.matches.aspx
GC's Collect:
http://msdn.microsoft.com/en-us/libr...c.collect.aspx
--
Kiron