Thomas' Tech Tips

Delete all files except certain type from a batch file

12 November 2023 - Thomas Damgaard

This Windows batch script will delete everything in a folder that is not of a certain type - in this excample .lnk (Windows shortcut):

@echo off
cd C:\tmp

:: Delete all files except .lnk
for %%f in (*) do (
    if "%%~xf" NEQ ".lnk" del "%%f"
)

:: Delete all directories
for /d %%d in (*) do (
    rmdir /s /q "%%d"
)

Note: The script first deletes all files (except .lnk files) and then deletes all directories in C:\tmp. Before running such scripts, always back up your data and test on a smaller scale or in a different directory to ensure it behaves as expected.

Filed under: bat, batch, howto, tips, windows

Back to article list