Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete all files in a folder (but not the folder itself) except for specific type files

I have a folder with lots of subfolders, each subfolders contain a .cpp file and multiple unimportant files. I want to run a command that go inside each subfolder and delete everything but the folder itself and the .cpp file.

I’ve tried this command but it just deleted the folder itself:

gci -Path $path | ? {!($_.Name -ilike "*.cpp")} | % { Remove-Item -Path $_.FullName }

Thank you in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If all folders have at least one .cpp in them, then you should only care about finding all files that don’t have a .cpp extension and deleting them so, add -Recurse, -File and -Exclude *.cpp to your Get-ChildItem call:

Get-ChildItem -Path $path -File -Recurse -Exclude *.cpp | Remove-Item
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading