This could as well be called “the beginner’s guide to .bat“. First of all, it a good idea to download some tool to help us start right away. I personally have found the best solutions to be the Microsoft Visual Studio Code and Notepad ++. Both are free and both do just great. Although writing a script can be done in notepad as well, I prefer some highlighting of an advanced editor. I think that based on my experience, people tend to think about writing a .bat script this way: “Yeah I have some basic knowledge od the cmd, writing a script will be easy”. I believe this is a mistake, as scripts works a bit differenent and people used to write C/C++/Java … will be quite confused about variable storing, code syntax and for cycles especially.
My first for-cycle written in .bat file took me about 2 +Hours to finish. Although it can be copied from web, I rather think about the commands, untill I am pretty sure what it exactly does. And as I say,there is no Int, unsigned int, auto ,float or double, there is only a string and the for-cycle runs on strings in fact. These are mostly file names and paths. I have added this sample code I believe will be pretty useful for people trying to write some basic directory browsing script. At first the quotations “” seems to be useless, but you wouldn’t believe how usefull they are when you are about to work with a strange filename/filepath, that contains special characters such as space,% or !. Also remember that each commands should have only one space before and after the commands. Well almost,except for setting variables …. and maybe something else :)
- A very good documentation can be found here: http://ss64.com/
REM Do not Display commands Written in the script!
REM Customizations - the second option is quite important
SETLOCAL EnableExtensions DisableDelayedExpansion
REM Clears the cmd screen
REM Get the current working directory:
REM Loop across all directories in the current folder
REM This is achieved by the "/D" argument.
FOR /D %%G IN ("*") DO (
REM #1 Loop across all files in the current folder by
REM Reading the output of the DIR command
REM #2 Do not forget the "tokens" part! Its helpful in case
REM Special characters appear in the path!
FOR /F "tokens=*" %%G IN ('DIR /B') DO (
REM #1 Basic example of if condition against a declared variable
REM #2 The "/I" Stands for in-sensitive comparison
REM #3 Variable can be set by "SET Var=Something" It is a string!
SET /I Variable=SomeString
IF Variable==SomeString (
ECHO String Match!
REM #1 Remember,that everything written in here is in the String Format!
REM #2 Do NOT add extra spaces near the "=" operator!
REM #3 The best docu is on the http://ss64.comWebsite
REM #4 Additional help: Start cmd.exe and type "help command"
REM #5 Always check code for spaces problems!
REM Most of mine come from missing or unnecessary spaces!