Useful DOS Commands

From time to time a DOS batch (“bat” or “cmd”) file needs to be written to perform some task or series of tasks. There are various commands that I seem to consistantly search for on the Internet. Here is a list of some of those useful DOS batch commands.

How to delete files equal to zero bytes in size.
Delete a specific file.

for /F %%A in ("deleteme.txt") do If %%~zA equ 0 del deleteme.txt

Delete all files equal to zero.

for %%F in (*.*) do (
if %%~zF LSS 1 del %%F

Use IF EXIST statement to check for the presense of a directory.

if not exist C:\win\nul goto nowindir
cd \win

Populating Array

set file_list=(file1.txt file2.txt file3.txt)
for %%i in %file_list% do echo %%i

How to conditionally take action if FINDSTR fails to find a string

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1 || xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

Multiple commands in a batch file loop

For %%f in (*.txt) do (
Command1 %1
Command2 %1

Stop script on DEL error

:: Delete all files, but exit if a file is locked.
for %%F in (*.*) do (
@echo Deleting %%F
ren %%F tmp 2> nul
@echo Cannot delete %%F, it is locked.
exit /b 1
del tmp
@echo off
set error=0
for /f %%i in ('del notepad2.exe 2^>^&1') do set error=1
echo %error%