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.

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

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
if ERRORLEVEL 1 (
@echo Cannot delete %%F, it is locked.
exit /b 1
)
del tmp
)
@echo off
setlocal
set error=0
for /f %%i in ('del notepad2.exe 2^>^&1') do set error=1
echo %error%

Source(s)
http://www.computerhope.com/issues/ch000754.htm
http://support.microsoft.com/kb/65994
http://superuser.com/questions/191224/populating-array-in-dos-batch-script
http://stackoverflow.com/questions/8530976/how-to-conditionally-take-action-if-findstr-fails-to-find-a-string
http://www.vistax64.com/powershell/138616-multiple-commands-batch-file-loop.html
http://stackoverflow.com/questions/560967/how-to-stop-batch-script-on-del-failure
http://www.dostips.com/DtCodeBatchFiles.php#Batch.FileDate