PowerShell: How to Delete All Files Not in a List


You can use the following syntax in PowerShell to delete all files in a directory that do not belong in a specific list:

$keep = Get-Content keep.txt

gci ./data1 | Where-Object { $keep -notcontains $_.name } | Remove-Item

This particular example deletes all files in the directory named data1 that do not belong in the list of filenames specified in the keep.txt file.

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

Example: How to Delete All Files Not in a List in PowerShell

Suppose that we would like to delete all files in a directory named data1 that do not belong in a list of filenames contained in a file named keep.txt.

We can use the Get-Content cmdlet to first view each of the filenames in the keep.txt file:

We can see that there there are three filenames saved in the keep.txt file:

  • team.csv
  • coaches.csv
  • managers.csv

Next, we can use the gci (an alias for Get-ChildItem) cmdlet to view all of the files in a directory named data1:

We can see that there are six total files in this directory.

Suppose that we would like to delete all of the files in this directory that do not belong in the list of filenames specified in the keep.txt file.

We can use the following syntax to do so:

$keep = Get-Content keep.txt

gci ./data1 | Where-Object { $keep -notcontains $_.name } | Remove-Item

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

PowerShell delete all files not in a list

Notice that when we run the gci command again, we can see that all files in the data1 folder that did not belong in the list of filenames specified in the keep.txt file have been deleted.

Related Tutorials

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

PowerShell: How to Delete Files Matching a Certain Pattern
PowerShell: How to Delete File if it Exists
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply