I need to count the number of occurrences within a single line from a string that contains backslashes and double backslashes.
I've tried using .Count, but it only counts the first instance within the line. When I try other commands, I usually get some kind of error regarding escape characters.
Here is the one line of data from the file c:\work\test.txt:
Occurrence1\\paul\dfs_app\MyFolder\QA2\testme1 Occurrence2\\paul\dfs_app\MyFolder\QA2\testme2
And here is my code:
$inString = "\\paul\dfs_app\MyFolder\QA2"
$file = "C:\work\test.txt"
$check = Get-Content $file | Where-Object { $_.Contains($inString) }
if ($check.Count -gt 0) {
Write-Host "Found" $check.Count.ToString().PadLeft(2, " ") "occurrences in " $file -ForegroundColor Yellow
}
It returns
Found 1 occurrences in C:\work\test.txt
but it should have found 2 occurrences.
Countdoes not count specific occurrences of your search string. YourWhere-Objectfilter returns the lines that contain your search string (regardless of how often it occurs), andCountreports the number of those lines. You don't get an extra line just because one line contains your search string more than once.