PowerShell: A Simple Formula for “Not Contains”


You can use the following syntax in PowerShell to only show rows in a file that do not contain specific strings:

(Get-Content $my_file) -notmatch [String]::Join('|',$dont_want)

This particular example will filter the rows in the file whose location is saved in the variable named my_file to only show the rows that do not contain any of the strings specified in the variable named dont_want.

The following examples show how to use this syntax in practice.

Example: How to Use “Not Contains” in PowerShell

Suppose we have a file named conferences.txt saved in the following location:

  • c:\users\bobbi\conferences.txt

We can use the following syntax to view the entire contents of this file:

$my_file = "c:\users\bobbi\conferences.txt"
Get-Content $my_file

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

We can see that the text file contains six lines that explain which conference various NBA teams belong to.

Suppose that we would like to filter this file to only show the rows that do not contain “Western” anywhere in the row.

We can use the following syntax to do so:

$dont_want = "Western"

(Get-Content $my_file) -notmatch [String]::Join('|',$dont_want)

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

PowerShell not contains

Notice that only the rows in the file that do not contain “Western” are shown.

Also note that we can specify multiple strings to filter on.

For example, we can use the following syntax to filter the file to only show rows that do not contain “Western” or “Knicks” anywhere in the row:

$dont_want = "Western", "Knicks"

(Get-Content $my_file) -notmatch [String]::Join('|',$dont_want)

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

PowerShell filter for rows that do not contain multiple strings

Only the rows that do not contain “Western” or “Knicks are shown.

Note: Feel free to include as many strings as you’d like in the dont_want variable.

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