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?
I used this, that works perfectly for me
Yes I know this is an old thread. I couldn't get any of the answers above to work in Powershell 5, so here is what I figured out:
This moves the -Recurse to Remove-Item instead of where the items are found.
In PowerShell 3.0 and below, you can try simply doing this:
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.