Delete all files and folders but exclude a subfolder

Select everything excluding what needs to be keep and pipe that to a delete command.

Say you have those folders

C:.
├───delme1
│   │   delme.txt
│   │
│   └───delmetoo
├───delme2
├───keepme1
│       keepmetoo.txt
│
└───keepme2

To delete everything but preserve the keepme1 and keepme2 folders.

Get-ChildItem -Exclude keepme1,keepme2 | Remove-Item -Recurse -Force

Other solutions are fine but I found this easy to understand and to remember.


In PowerShell 3.0 and below, you can try simply doing this:

Remove-Item -recurse c:\temp\* -exclude somefile.txt,foldertokeep

Unless there's some parameter I'm missing, this seems to be doing the trick...

Edit: see comments below, the behavior of Remove-Item has changed after PS3, this solution doesn't seem applicable anymore.


I used the below and just removed -Recurse from the 1st line and it leaves all file and sub folders under the exclude folder list.

   Get-ChildItem -Path "PATH_GOES_HERE" -Exclude "Folder1", "Folder2", "READ ME.txt" | foreach ($_) {
       "CLEANING :" + $_.fullname
       Remove-Item $_.fullname -Force -Recurse
       "CLEANED... :" + $_.fullname
   }

Get-ChildItem -Path  'C:\temp' -Recurse -exclude somefile.txt |
Select -ExpandProperty FullName |
Where {$_ -notlike 'C:\temp\foldertokeep*'} |
sort length -Descending |
Remove-Item -force 

The -recurse switch does not work properly on Remove-Item (it will try to delete folders before all the child items in the folder have been deleted). Sorting the fullnames in descending order by length insures than no folder is deleted before all the child items in the folder have been deleted.

Tags:

Powershell