DonCan94
DonCan94

Reputation: 15

Search for filenames containing two or more occurrence of a specific string using PowerShell

I would like to print all files of a directory which contain a specific string multiple times in their name (not in the file itself). Is there a way to do this with Powershell?

Edit:

This is what I have so far:

Get-ChildItem -Path "path" -Recurse -Filter *string*

With this I get all the files which contain that string at least once, but I only need the ones where it occures twice or more.

Upvotes: 1

Views: 647

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

I only have this: Get-ChildItem -Path "path" -Recurse -Filter *string*

Great!

Now all you need to do is repeat the word:

Get-ChildItem -Path "path" -Recurse -Filter *string*string*

If the substring in question has spaces, you'll need to quote the string:

Get-ChildItem -Path "path" -Recurse -Filter '*looking for this*looking for this*'

If the string contains wildcard character literals (like [ or ]), you can escape it like this:

$escapedString = [wildcardpattern]::Escape("string [ with special ] characters")

So the whole thing becomes:

$substring = "string we're [looking] for"
$searchTerm = [wildcardpattern]::Escape($substring)
Get-ChildItem -Path "path" -Recurse -Filter "*$searchTerm*$searchTerm*"

Upvotes: 1

Related Questions