How can I delete files in a folder while keeping specific ones?

0
35
Asked By CrazyPineapple42 On

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!

5 Answers

Answered By StrategySavant33 On

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!

Answered By FunkyMonkey89 On

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!

Answered By QuickFix47 On

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!

Answered By WittyWizard22 On

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!

TechieTed77 -

That's a pretty good method! Just ensure you have backups before you delete anything.

FunkyMonkey89 -

True! It's always safer to double-check everything before hitting delete.

Answered By CodingNinja100 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.