How can I delete files in a folder while keeping specific ones?
Asked by
dough+rise
I'm looking for a command that lets me delete all files in a specific folder while preserving the folder structure. I want to keep all files named "config.json", which are scattered throughout the subfolders at various depths. I'm trying to delete around 30,000 files, so I need something efficient. I've spent about half an hour trying to figure this out without success. Any help would be greatly appreciated!
Answers
Here's a straightforward one-liner you can use:
`Get-ChildItem -Path "C:MyPath" -Recurse -File | Where-Object { $_.Name -ne 'config.json' } | Remove-Item -WhatIf`
Make sure to test it with `-WhatIf` first to see what it would do without actually deleting files. It's a simple solution, but the where-object part may be slow if you have many files.
Reply to this answer
If you're just tackling this task once, consider a simpler approach. You can open the folder in your file explorer, search for '*', and then sort the results by name. This way, you can select the ranges of files to delete while keeping the 'config.json' files together. Just be prepared; with 30,000 files, it may take some time to process any solution!
Reply to this answer
You could also filter proactively using a method like this:
`Get-ChildItem -Path "C:MyPath" -Recurse -File -Exclude 'config.json' | Remove-Item -WhatIf`
Itโs a bit less flexible, but it should be quicker with large file counts like yours. Just remember to check everything thoroughly before running it for real!
Reply to this answer
Have you shared what you've tried so far? It sounds like there might be a couple of commands you can combine to get this done easily!
Reply to this answer
Hereโs another example that structures it differently:
```powershell
$FullName = '*config*.json'
$Params = @{ Path = "C:MyPath"; Recurse = $true; Force = $true; Exclude = $FullName }
GCI @Params -EA:'0'
# Remove content recursively
$DeleteSubContent = (GCI @Params -EA:'0').FullName
Del -Path $DeleteSubContent -Recurse -CF:$false -Force -Verbose
```
This allows you to handle it all effectively. Always check your results carefully before executing the delete command!
Reply to this answer
Add your answer
Answers are reviewed before publication.
STOCK.pot.lid: That's a pretty good method! Just ensure you have backups before you delete anything.
molecular sieve fan: True! It's always safer to double-check everything before hitting delete.