Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all files and folders but exclude a subfolder

Tags:

powershell

I have a folder where I need to delete all files and folders except a small list of files and folders.

I can already exclude a list of files, but don't see a way to exclude a folder and its contents.

Here is the folder structure:

|-C:\temp  \-C:\temp\somefile.txt  \-C:\temp\someotherfile.txt | |-C:\temp\foldertodelete    \-C:\temp\foldertodelete\file1.txt | |-C:\temp\foldertokeep |  \-C:\temp\foldertokeep\file2.txt 

I want to keep somefile.txt and the folder foldertokeep and its content.

This is what I have right now:

Get-ChildItem -Path  'C:\temp' -Recurse -exclude somefile.txt | Remove-Item -force -recurse 

This really does not delete somefile.txt. Is there a way to exclude folder foldertokeep and its content from the delete list?

like image 479
Mathias F Avatar asked Feb 08 '13 15:02

Mathias F


People also ask

How do I exclude a subfolder in PowerShell?

To get only directories, use the Directory parameter and omit the File parameter. To exclude directories, use the File parameter and omit the Directory parameter, or use the Attributes parameter. To get directories, use the Directory parameter, its "ad" alias, or the Directory attribute of the Attributes parameter.

How do you remove all files from subfolders and relocate them to one folder?

In the search box (top right), type NOT kind:folder . You will now see a list of all files in your current folder and all its subfolders. Use Control-A to select all the files. Now you can move them all to another folder.

How do I select all except one folder?

Select multiple files or folders that are not grouped together. Click the first file or folder, and then press and hold the Ctrl key. While holding Ctrl , click each of the other files or folders you want to select.


1 Answers

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.

like image 195
mjolinor Avatar answered Sep 17 '22 18:09

mjolinor