PowerShell: Keep X Number of Files and Delete the Rest


You can use the following syntax in PowerShell to keep X number of files in a particular directory and delete the rest:

Get-ChildItem -Recurse -File |
  Sort CreationTime -desc |
  Select -skip 5 |
  Remove-Item -Force

This particular example will keep the 5 most recently created files in the current directory and delete all other files.

Here is what the various commands do:

  • Get-ChildItem -Recurse -File: Recursively retrieve all files in current directory and subfolders
  • Sort CreationTime -desc: Sort files from newest to oldest based on creation date
  • Select -skip 5: Select all files except the first 5
  • Remove-Item -Force: Delete selected files, using -Force to include read-only and hidden files

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

Example: How to Keep X Number of Files and Delete the Rest in PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\data6

We can type Get-ChildItem -Recurse -File to list out all files in this current directory:

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

Suppose that we we would like to only keep the 5 most recently created files and delete the rest.

We can use the following syntax to do so:

Get-ChildItem -Recurse -File |
  Sort CreationTime -desc |
  Select -skip 5 |
  Remove-Item -Force

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

PowerShell keep X files and delete the rest

Notice that when we use the Get-ChildItem cmdlet again to view all of the files in the current directory that only the 5 most recently created files are left.

All other files have been deleted.

Note: Feel free to change the value 5 after the -skip command to keep a different number of files instead.

Related Tutorials

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

PowerShell: How to Delete All Files with Specific Extension
PowerShell: How to Rename File Extension of Multiple Files
PowerShell: How to List All Files in Directory to Text File

Leave a Reply