Search code examples
windowsrecursioncmd

Delete file with same name contained in different sub-folders


For some reason, I have a copy of dismhost.exe in a lot of folders, inside temp folder; what I want to do is delete every instance of it, which are inside folders inside temp.

So the structure is as follows:

/temp
 /folder1
  dismhost.exe
 /folder2
  dismhost.exe
 /folder3
  dismhost.exe
 ...

I first tried

rm ./*/dismhost.exe

but then I remembered there is no rm in windows, so I tried with rd with same arguments. That raised an error, saying that the * modifier is not valid.

How can I achieve this?


Solution

  • This can be done using a FOR loop iterating over a list of files returned by a recursive DIR search. When you are satisfied with the output, remove ECHO in order to actually delete the files.

    FOR /F "usebackq tokens=*" %f IN (`DIR /S /B /A:-D \temp\dismhost.exe`) DO (ECHO DEL "%~f")
    

    If this is placed into a .bat script, be sure to double the % characters on the variable.

    FOR /F "usebackq tokens=*" %%f IN (`DIR /S /B /A:-D \temp\dismhost.exe`) DO (
        ECHO DEL "%%~f"
    )