slashbrackets
slashbrackets

Reputation: 256

In Powershell how do I find file names that contains text or files that have the text in them

I'm searching through directories recursively. I want to find files that contain text i'm looking for OR the text is in the content of the file.

For example, if I search for "hello", i'd normally do this:

Find matching file names:

get-childitem -filter "*hello*"

Find files that have text in them:

get-childitem -recurse | select-string -pattern "*hello*"

But I want to do both at the same time. Which means you could have files that don't have "hello" in the name but it does appear in the contents of the file. Or visa versa.

EDIT: I considered using where-object with an -or but having trouble figuring out how to construct that properly.

EDIT: My mistake, meant to include select-string in the example.

Ideas?

Thanks

Upvotes: 3

Views: 5903

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 59782

I don't think its possible to use -Filter because you might be excluding those files which's content could contain the word you're looking for.

An easy approach I could think of, is looping through all files in $startPath recursively and, if the word is contained in the file's name, go to the next iteration with continue or break if you want to stop the loop at first finding, and of course, use -Raw for Get-Content:

$startPath = 'C:\path\to\startFolder'
$magicWord = 'hello'

foreach($file in Get-ChildItem $startPath -Recurse -File)
{
    if($file.Name -match $magicWord)
    {
        $file
        continue
        # or break here if you want to stop the loop
    }

    if((Get-Content $file.FullName -Raw) -match $magicWord)
    {
        $file
        # break here if you want to stop the loop
    }
}

Not sure if using this would be faster or not:

if([system.io.file]::ReadAllText($file.FullName) -match $magicWord)
{
    ...
}

Upvotes: 2

Related Questions