Windows – How to delete all files that don’t have a certain string in their name

batchfile managementpowershellregexwindows

I have seen Deleting all files that do not match a certain pattern – Windows command line

However, I have not seen anything regarding how to delete everything that does not contain a certain string within its file name.

How can I delete all zip (other files should not be effected) files in a folder and its subfolders that don't have "MS" (case sensitive) in their file name.

These letters may be next to other letters (eg. a file names "ABCMSABC" should be kept because it has "MS" in it, but all other files should be deleted). Multiple files will have "MS" in them.

Best Answer

How can I delete zip files in a folder/subfolders that don't have "MS" in their name?

Use the following batch file:

@echo off
setlocal disableDelayedExpansion
for /f "usebackq tokens=*" %%i in (`dir /a:-d /b /s *.zip ^| findstr /v "[\\][^\\]*MS[^\\]*$"` ) do (
  echo del /s /q %%i
)
endlocal

Notes:

  • Remove the echo when you are happy with what the batch file will do.
  • Answer updated as per comment by dbenham to allow for directories containing the string "MS"
  • Answer updated to handle filenames containing spaces.

Further Reading

Related Question