16

I am trying to find all files, which does not contains a selected string. Find files which contains is easy:

gci | select-string "something"

but I do not have an idea how to negate this statement.

Piotr Stapp
  • 18,790
  • 11
  • 66
  • 112

3 Answers3

23

You can use Where-Object;

gci | Where-Object { !( $_ | Select-String "something" -quiet) }
Joachim Isaksson
  • 170,943
  • 22
  • 265
  • 283
15

I'm not sure if it can be done without the foreach-object but this works:

gci |foreach-object{if (-not (select-string -inputobject $_ -Pattern "something")){$_}}
alroc
  • 26,843
  • 6
  • 49
  • 94
  • I would also use the switch `-List`, i.e. `Select-String ... -List` in order to make this more effective, presumably, because we do not need all the found matches. – Roman Kuzmin Jul 30 '13 at 11:40
  • And one more thing. This code returns directories as well. In order to avoid this I would use `gci -File` (in PowerShell V3, at least). – Roman Kuzmin Jul 30 '13 at 11:42
  • 6
    `Where-Object` can make it even simpler. `gci -File | Where-Object {!(Select-String -InputObject $_ -Pattern "something" -List)}` – Roman Kuzmin Jul 30 '13 at 11:49
  • I found this "ls . -name yourfile*.txt | where {-not (select-string -path $_ -pattern "stringYouDontLike" -Quiet)}" on https://social.technet.microsoft.com/Forums/scriptcenter/en-US/b20748b9-57f2-474d-b90f-8d09fcf37fb7/get-filename-that-does-not-contain-the-specified-string?forum=winserverpowershell – Doug J. Huras Nov 08 '17 at 20:42
2

As mentionend in How do I output lines that do not match 'this_string' using Get-Content and Select-String in PowerShell?

Select-String has the NotMatch parameter.

So you could use it:

gci | Select-String -notmatch "something"
Community
  • 1
  • 1
Bohne
  • 4,001
  • 1
  • 15
  • 22
  • 2
    My guess is that the downvotes are due to this approach returning every single line in every single file that doesn't match the pattern specified. While I'm sure there's a use case for that, the question is asking for a way to just list the files that don't contain your search pattern, and this approach isn't very helpful for that. – Nick Ligerakis Apr 25 '18 at 13:40
  • This will always return `True`. Since there are blank lines in the output of `gci` (a.k.a. `Get-ChildItem`), there will always be lines that do not match the provided pattern. – Vince May 04 '21 at 08:16