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
I used this, that works perfectly for me
Get-ChildItem -Path 'C:\Temp\*' -Recurse | Where-Object {($_.FullName -notlike "*windirstat*") -and ($_.FullName -notlike "C:\Temp\GetFolderSizePortable*")} | Remove-Item -Recurse
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.
@powershell Remove-item C:\Random\Directory\* -exclude "MySpecialFolder", "MySecondSpecialFolder" -force -erroraction 'silentlycontinue'
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:
Get-ChildItem -Path $dir -Exclude 'name_to_ignore' |
ForEach-Object {Remove-Item $_ -Recurse }
This moves the -Recurse to Remove-Item instead of where the items are found.
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.
C:.
├───delme1
│ │ delme.txt
│ │
│ └───delmetoo
├───delme2
├───folder1
│ keepmesafe.txt
│
└───folder2
So you want to delete everything and preserver the folder1 and folder2
Get-ChildItem -Exclude folder1,folder2 | Remove-Item -Recurse -Force
There are many other solutions but I found this easy to understand and 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.