windowsbatch-filedirectorydelete-filedel

Wildcards not working as expected in the del command


The goal is to delete all jpg and png files in a directory and it's subdirectories in Windows 10. The directory containing the files is the same as where the script is executed.

Following batch file snippet is designed to perform that task. However, the files aren't being deleted.

del "ToDelete/*/*.jpg"
del "ToDelete/*/*.png"

The suspicion is that the wildcards might not be recognized. How can they be correctly integrated into the argument?


Solution

  • Wildcards can only be used in the last element of a path. You can use a for /D loop to loop through the parent directories of the files to delete:

    for /D %%D in ("ToDelete\*") do (    
        del "%%~D\*.jpg" "%%~D\*.png"
    )
    

    Add the /Q switch to delete without prompting.

    Note: In Windows, use \ as path separators as / might cause trouble.


    In case you want to delete files in any directory depth, use switch /S of del:

    del /S "ToDelete\*.jpg" "ToDelete\*.png"
    

    Add the /Q switch to delete without prompting.