PowerShell: How to Delete Files Matching a Certain Pattern


You can use the following syntax in PowerShell to delete all files in a directory whose name matches a certain pattern:

Get-ChildItem $Path | Where{$_.Name -Match "new"} | Remove-Item

This particular example deletes all files in the current directory that contain the string “new” somewhere in the file name.

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

Related: How to Delete All Files with Specific Extension in PowerShell

Example: How to Delete All Files Matching a Certain Pattern Using PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\OneDrive\Documents\test_data

We can type Dir to list out all files in this current directory:

We can see that there are four files in this directory:

  • my_data.txt
  • my_newest_data.txt
  • new_data.txt
  • some_old_data.txt

Suppose that we would like to delete all files that contain “new” in the file name.

We can use the following syntax to do so:

Get-ChildItem $Path | Where{$_.Name -Match "new"} | Remove-Item

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

PowerShell delete files matching pattern

We can see that we were able to successfully delete the two files in the directory that contained “new” somewhere in the file name:

  • my_newest_data.txt
  • new_data.txt

When we ran the Dir command again, we could see that the two files without “new” in the name were left untouched.

Note: The Match statement in PowerShell is case-sensitive. For example, if we instead searched for “NEW” then the two files with “new” in the file name would still have been deleted.

Related Tutorials

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

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Text with Wildcard
PowerShell: How to Replace Special Characters in String

Leave a Reply