I have a diectory 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 dont see a way to exclude a folder.
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 realy does not delete somefile.txt. Is there a way to exclude folder foldertokeep and its content from the delete list?
According to MSDN
Remove-Item
has a known issue with the-exclude
param. Use this variant instead.This would also help someone...
I ran into this and found a one line command that works for me. It will delete all the folders and files on the directory in question, while retaining anything on the "excluded" list. It also is silent so it won't return an error if some files are read-only or in-use.
This would also help someone...
Adding a variable for PATH_GOES_HERE that is empty or isn't defined prior can cause a recursive deletion in the user directory (or C:\windows\system32 if the script is ran as admin). I found this out the hard way and had to re-install windows.
Try it yourself! (below will only output the file directories into a test.txt)
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.
I use this approach assuming you want to exclude some files or folders at root level but then you want to delete everything inside them.
So you want to delete everything and preserver the folder1 and folder2
There are many other solutions but I found this easy to understand and remember.