Batch file basics
Disable echo:
@echo off
Loops over fixed values:
for %%a in (a b c) do (
echo %%a
)
echo %%a
)
Variables:
set somevar=myvalue
echo %somevar%
echo %temp%
echo first param=%1
echo second param=%2
echo %somevar%
echo %temp%
echo first param=%1
echo second param=%2
Check file existence:
if exist somefile.ext del somefile.ext
if not exist somefile.ext echo no file
if not exist somefile.ext echo no file
Check variable existence:
if defined somevar echo somevar=%somevar%
Numeric comparison:
if 24 gtr 30 (echo GREATER) else echo LESSEQ
rem EQU equal to
rem NEQ not equal to
rem LSS less than
rem LEQ less than or equal to
rem GTR greater than
rem GEQ greater than or equal to
rem EQU equal to
rem NEQ not equal to
rem LSS less than
rem LEQ less than or equal to
rem GTR greater than
rem GEQ greater than or equal to
Prompt:
set /p name=What is your name?
echo Your name is %name%
echo Your name is %name%
Labels:
goto :mylabel
echo blah blah
:mylabel
echo Just skipped blah blah
echo blah blah
:mylabel
echo Just skipped blah blah
Numeric expression in variable:
set /a num=0
:numbers
set /a num=%num%+1
if %num% EQU 10 (goto :next) else (echo %num%)
goto :numbers
:next
echo done
:numbers
set /a num=%num%+1
if %num% EQU 10 (goto :next) else (echo %num%)
goto :numbers
:next
echo done
Pause:
pause
Pass all arguments to another executable:
set args=%1
shift
:start
if [%1] == [] goto done
set args=%args% %1
shift
goto start
:done
.\SomeExecutable.exe %args%
shift
:start
if [%1] == [] goto done
set args=%args% %1
shift
goto start
:done
.\SomeExecutable.exe %args%
String comparison:
@echo off
set /p ans=Are you sure?
if "%ans%" == "y" goto :dowork
if "%ans%" == "Y" goto :dowork
goto :eof
:dowork
echo Work is being done...
set /p ans=Are you sure?
if "%ans%" == "y" goto :dowork
if "%ans%" == "Y" goto :dowork
goto :eof
:dowork
echo Work is being done...