I want to delete all files that are not .doc under Documents directory. How can I do this with a windows batch file or in the command prompt?
@echo off setlocal enableextensions disabledelayedexpansion set "folder=x:\somewhere\documents" for /f "delims=" %%a in (' dir /b /s /a-d "%folder%" ^| findstr /i /v /e /l /c:".doc" ') do echo del "%%a"
This code executes a dir command (only file paths/names
/s, without folders in the list
/a-d) to retrieve the list of files under the documents folder. This list is filtered with
findstr to only get, ignoring case
/i, the lines that do not contain
/v at the end of the line
/e the literal
This command is executed from a
for command that will process each line of the output. For each line, the replaceable parameter
%%a will hold the path/name of the file, so in the
do clause we remove the indicated file.
del operations are only echoed to console. If the output is correct, remove the
Test this on a sample set of files.
@echo off set "folder=c:\documents" attrib +h "%folder%\*.doc" /s del "%folder%\*.*?" /s attrib -h "%folder%\*.doc" /s
use the underappreciated
forfiles /s /c "cmd /c if @isdir NEQ TRUE if [@ext] NEQ [doc] del @path"