1. Home
  2. Windows

How to delete files but keep folders on Windows 10

Folders aren’t hard to create but if you have a complex directory structure that took time to create (and name properly), you probably don’t want to recreate it unless you have to. You can copy a folder structure pretty easily and ignore the files in it but, if you’d just like to delete all the files in the folder while still retaining the complex folder structure that you’ve created, you can do that as well. Between the two methods, you can take your pick. We’re going to explain how you can delete files but keep folders with a simple PowerShell command.

Delete files but keep folders

You do not need admin rights for this unless you are deleting files from the root of the C drive. If you’re deleting them from your user folder, or any other drive, internal or external, normal user rights will be enough.

Open PowerShell and run the command below. Replace the ‘path-to-folder’ with the complete path to the folder that you want to delete files from. This command is going to delete all files from this folder, and any and files that are in sub-folders under it. The delete action does not send the files to the Recycle bin so make sure you back them up first.

Command

Get-ChildItem -Path "path-to-folder" -Include *.* -File -Recurse | foreach { $_.Delete()}

Example

Get-ChildItem -Path "D:\Desktop\Jan 13 - 17" -Include *.* -File -Recurse | foreach { $_.Delete()}

This command can be modified to target a specific type of file as well. To do that, you need to change the following;

*.*

Replace the second asterisk with the file extension for the files you want to target. For example, if you’d like to delete all text files from a folder, you will use the command below.

Get-ChildItem -Path "path-to-folder" -Include *.txt -File -Recurse | foreach { $_.Delete()}

All other files will be left untouched. As before, the files will not be sent to the Recycle bin so back them up before you delete them. This command can also be utilized to delete a file that has the same name and that exists in multiple folders e.g., image.png. Again, you will modify the bit with the two asterisks. The command will look like the following.

Get-ChildItem -Path "path-to-folder" -Include image.png -File -Recurse | foreach { $_.Delete()}

There are advanced file deletion utilities that can do this but the best ones are often complex to figure out. This command is simple to run and there is far less chance of error since nothing will result in folders being deleted.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.