powershellcommandcommand-prompt

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!


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