PowerShell: How to Use Where-Object with -notlike


You can use the Where-Object cmdlet along with the -notlike operator in PowerShell to filter for strings that do not match a particular pattern.

Here is one way to use this syntax in practice:

Get-ChildItem | Where-Object {$_.Name -notlike "*coaches*"}

This particular example use the Get-ChildItem cmdlet to retrieve all folders and files in the current directory and then uses the Where-Object cmdlet to filter the results to only show the items that do not contain the string “coaches” in the name.

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

Example: How to Use Where-Object with -notlike in PowerShell

Suppose that we use the Get-ChildItem cmdlet to first view all files and folders in our current directory:

We can see that our current directory contains seven total files.

We can use the following syntax with the Where-Object cmdlet to only return the files that do not contain the string “coaches” in the filename:

Get-ChildItem | Where-Object {$_.Name -notlike "*coaches*"}

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

PowerShell Where-Object -notlike

Notice that this returns only the files that do not contain the string “coaches” anywhere in the filename.

Note that we can also use the -notlike operator to exclude specific file types from the results.

For example, we can use the following syntax to only return the filenames that do not have .txt extensions:

Get-ChildItem | Where-Object {$_.Name -notlike "*.txt"}

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

Notice that this returns only the files that do not have .txt file extensions.

Note: You can find the complete documentation for the -notlike operator in PowerShell here.

Related Tutorials

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

PowerShell: A Simple Formula for “If Like”
PowerShell: A Simple Formula for “Not Contains”
PowerShell: How to Replace Text in String
PowerShell: How to Replace Special Characters in String

Leave a Reply