Recursively find text in files (PowerShell) Recursively find text in files (PowerShell) powershell powershell

Recursively find text in files (PowerShell)


Your question seems to boil down to: I want to find all files in a directory that contain the carriage return. Is there any reason why these answers are not adequate?

For example:

This should give the location of the files that contain your pattern:

Get-ChildItem -recurse | Select-String -pattern "dummy" | group path | select name


You could use Select-String to find patterns in a group of files, however this will only search for the pattern within each line of text. It will not work in your case because you want to search for the line separator.

An easier way is to use Get-Content, this convert a file to an array of strings, one item per line. Therefore any file that has a return and a line feed will produce an array with more than one item. Try something like this:

Get-ChildItem -recurse | ? {(Get-Content $_.FullName).count -gt 1}

If your files are quite large and you want to speed it up then add a -TotalCount like this:

Get-ChildItem -recurse | ? {(Get-Content $_.FullName -TotalCount 2).count -gt 1}

This will only find where the return and line feed are together, if you want instances where they could appear on their own then you will need to force Get-Conent to not read the file as an array of string but one big string instead. Something like this:

Get-ChildItem -recurse | ? {[regex]::Matches((Get-Content $_FullName -Raw), '[\r\n]+').Count -gt 0}