List file names in a folder matching a pattern, excluding file content

Viewed 125077

I am using the below to recursively list all files in a folder that contains the $pattern

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

But it seems it both list files having the $pattern in its name and in its content, e.g. when I run the above where $pattern="SAMPLE" I get:

C:\tmp\config.include
C:\tmp\README.md
C:\tmp\specs\SAMPLE.data.nuspec
C:\tmp\specs\SAMPLE.Connection.nuspec

Now:

C:\tmp\config.include
C:\tmp\README.md

indeed contains the SAMPLE keywords/text but I don't care about that, I only need the command to list file names not file with content matching the pattern. What am I missing?

Based on the below answers I have also tried:

$targetDir="C:\tmp\"
Get-ChildItem $targetDir -recurse | where {$_.name -like "SAMPLE"} | group path | select name

and:

$targetDir="C:\tmp\"
Get-ChildItem $targetDir -recurse | where {$_.name -like "SAMPLE"} | select name

but it does not return any results.

6 Answers

I went through the answer by @Itchydon

but couldn't follow the use of '-like' $pattern.

I was trying to list files having 32characters(letters and numbers) in the filename.

PS C:> Get-ChildItem C:\Users\ -Recurse | where {$_.name -match "[a-zA-Z0-9]{32}"} | select name

or

PS C:> Get-ChildItem C:\Users\010M\Documents\WindowsPowerShell -Recurse | Where-Object {$_.name -match "[A-Z0-9]{32}"} | select name

So, in this case it doesn't matter whether you use where or where-object.

To complement the excellent answer by @mklement0, you can ask Powershell to print the full path by appending a pipe as follows:

Get-ChildItem -Recurse -ErrorAction SilentlyContinue -Force -Filter "*sample*" | %{$_.FullName}

Note: When searching folders where you might get an error based on security, hence we use the SilentlyContinue option.

You can use select-string directly to search for files matching a certain string, yes, this will return the filename:count:content ... etc, but, internally these have names that you can chose or omit, the one you need is the "filename" to do this pipe this into "select-object" choosing the "FileName" from the output.

So, to select all *.MSG files that has the pattern of "Subject: Webservices restarted", you can do the following:

Select-String -Path .*.MSG -Pattern 'Subject: WebServices Restarted' -List | select-object Filename

Also, to remove these files on the fly, you could pip into a ForEach statement with the RM command as follows:

Select-String -Path .*.MSG -Pattern 'Subject: WebServices Restarted' -List | select-object Filename | foreach { rm $_.FileName }

I tried this myself, works 100%.

I hope this helps

Related