PowerShell One Liner For Showing All Files In A Folder That Contain A String
Posted on September 29, 2019
- and tagged as
- powershell
Quick one today, this is probably the third or fourth time in the last few months I’ve needed to parse multiple files searching for a string, and each time I spend a little bit more time thinking about how to quickly do it than I’d like. So here it is for future reference, a quick one liner to print out the files that contain a string in a folder.
Get-ChildItem -File -Recurse -Force | % { if ((Get-Content $_.FullName) -match "SEARCH_STRING") {$_.FullName}}
This assumes there are only text files in the folder, I recommend adding filters to Get-ChildItem
if you have other file types too.
Note the -Force
argument, this is needed to catch hidden files. Get-ChildItem
has a -Hidden
option but this only shows hidden files whereas -Force
will show both.
Lastly, this should only be used for small files as PowerShell will read the entire file into memory, so beware.
Improving performance and reducing memory usage
December 2023 - update time. I needed to parse a large number of files, some of which were larger than the above snippet could easily handle - the PowerShell process was consuming upwards of 7GB of memory. So let’s address that with a more performant version. This uses a stream so each file does not need to be read into memory.
$MatchString = "SEARCH_STRING"
Get-ChildItem -File -Recurse -Force -ErrorAction SilentlyContinue | % {
$FilePath = $_.FullName
$Reader = New-Object System.IO.StreamReader -Arg $FilePath
while ($Line = $Reader.ReadLine()) {
if ($Line -match $MatchString) { $FilePath }
}
$Reader.Close()
}