Windows Dos Batch Files
@echo off IF .%1 == . ( GOTO ERROR ) ELSE IF .%1 == .goat ( SET MSG=echo good guess ) ELSE ( SET MSG=echo nope %1 is wrong ) IF .%2 == . ( GOTO ACTION ) ELSE IF .%2 == .goat ( SET MSG=%MSG% ^& echo good guess ) ELSE ( SET MSG=%MSG% ^& echo nope %2 is wrong ) IF NOT .%3 == . ( GOTO ERROR ) :ACTION echo. echo Thanks for playing. %MSG% GOTO DONE :ERROR echo. echo doit ^<guess^>; [^<another^>;] echo. echo Example: doit mouse echo. :DONE
You don't need quotes. But in order to check for empty vars you can prefix with anything, for example a dot. You get the args via %1, %2, etc. You set vars using anyname and later read them via %anyname%. You can mimic functions via GOTO. Special characters like <>& need to be escaped via ^ in order to be printed. You can print an empty line via echo followed by a dot, but you can't embed a line break in an echo. You can build a var that is a series of echo commands separated via the & symbol, which indicates that a new command is starting.
The round bracket in Windows7 path names can wreak havoc with your batch scripts. Work around this by finding its short path name and using that instead.
C:\Program Files (x86)> cd ../ C:\>dir /x 07/16/2013 12:58 PM <DIR> PROGRA~1 Program Files 07/16/2013 12:58 PM <DIR> PROGRA~2 Program Files (x86)
You can build custom timestamps from the %DATE% variable using :~pos,length variable expansion.
C:\Temp>echo %DATE% 05/10/2013 C:\Temp>echo %DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2% 2013_10_05
For Each Line
Sometimes you have a command that will output a bunch of values, one per line. If you want to operate on each of these, you can use a for loop. The
usebackq lets you input from the output of a command rather than from a file. In my case I needed to be in a specific location to execute my command hence the
PUSHD/POPD. Note that if you only want to operate on part of the line, you can use a more complicated
@echo off PUSHD Z: FOR /F "usebackq tokens=*" %%G IN (`yourCommand yourArgs`) DO ( echo %%G ) POPD