Reputation: 376
I am not an expert at PowerShell. I am trying to search for a multi-line string in a file, but I don't get the desired result.
Here is my code:
$search_string = @("This is the first line`nThis is the second line`nThis is the third line")
$file_path = "log.txt"
$ret_string = @(Get-Content -Path $file_path | Where-Object{$_.Contains($search_string)}).Count
Write-Host $ret_string
$ret_string
is set to 0
although "log.txt"
contains exactly the same content as $search_string
.
Upvotes: 1
Views: 3284
Reputation: 22821
A few problems here:
\r\n
as a new line.Contains
function will return a boolean value, so won't help you retrieve a count$search_string
does not need to be an arrayYou can use the -Raw
parameter to get the entire file contents as a string. You're also better off using a regular expression to search here. Try:
$search_string = "This is the first line`r`nThis is the second line`r`nThis is the third line"
$file_path = "log.txt"
$ret_string = (Get-Content -raw -Path $file_path | Select-String $search_string -AllMatches | % { $_.matches}).count
This will return a count of all the occurrences of $search_string
in the file
Upvotes: 5
Reputation: 200213
Get-Content
returns an array of strings (one per line), each of which is checked separately in your Where-Object
condition. You need to read the file as a single string for your check to work:
Get-Content $file_path | Out-String | Where-Object { ... }
On PowerShell v3 or newer the cmdlet has a parameter for reading the raw file:
Get-Content $file_path -Raw | Where-Object { ... }
Note, however, that you may need to adjust your condition to check for `r`n
rather than just `n
, particularly with the first approach.
Upvotes: 4