PowerShell: How to Find Files that Do Not Contain Specific String


You can use the following syntax in PowerShell to find all files in a particular folder that do not contain a specific string on any line in the file:

Get-ChildItem | Where-Object { !($_ | Select-String "Mavs") } | Select Name

This particular example will return the filenames of each file in the current directory that do not contain the string “Mavs” on any line in the file.

Here is what the various commands do:

  • Get-ChildItem: Retrieve each file in the current directory
  • Where-Object: Filters files based on some condition
  • !($_ | Select-String “Mavs”): Selects a file only if it does not contain the string “Mavs” on any line
  • Select Name: Returns only the filename

The following example shows how to use this syntax in practice.

Example: Find All Files that Do Not Contain a Specific String in PowerShell

Suppose that our current directory contains the following three text files:

  • teams1.txt
  • teams2.txt
  • teams3.txt

We can use the Get-Content cmdlet to view the contents of each of these files:

Each of the files contain information about various basketball team names.

Suppose that we would like to find all of the files that do not contain the string “Mavs” on any line in the file.

We can use the following syntax to do so:

Get-ChildItem | Where-Object { !($_ | Select-String "Mavs") } | Select Name

The following screenshot shows how to use this syntax in practice:

PowerShell find files that do not contain specific string

This returns the following files:

  • teams2.txt
  • teams3.txt

This tells us that the string “Mavs” does not occur in either of these files.

Feel free to replace “Mavs” with any other string that you would like to search for in your own files.

Note: You can replace Select Name with Select FullName to instead return the full path to files instead of just the filenames.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply