DOS Batch is the Windows equivalent of shell scripting and can be used to perform all sorts of different actions. Anything that you type into a DOS prompt on a Windows machine can be used in a bat file to quickly do something that you would otherwise have to repeat many times over. To create a bat file just make a file and give it the extension "bat". If you run a DOS prompt and navigate to the directory that the bat file exists in you can type the name of the file to get it to do certain actions. If you called your file "action.bat" you can run it by typing "action" or "action.bat". Starting with a simple example, if you want to print the contents of a file to screen then you need the type command, followed by the file.
However, this puts a lot of rubbish on the screen. If you wanted to create a backup of that file then you would write the following.
type file.txt > file_back.txt
This takes the contents of one file and puts it in another. To loop through every file in a directory you need to use the following line.
FOR %%i IN (*.*) DO echo %%i
This code will loop through the contents of a directory and print out each file name to screen. This will also list the bat file that you put in the directory so another solution might be to run the bat file from the directory above and use the following code.
FOR %%i IN (directory\*.*) DO echo %%i
The following snippet of code takes the previous example and does something useful. It loops through the directory and puts every file name that it finds into a file called list.txt.
FOR %%i IN (directory\*.*) DO echo %%i >> list.txt
The >> symbol will append any content to the file, so for every iteration of the loop the list.txt file gets one line bigger, until all of the files have been listed. In an example directory the following would be seen in the list.txt file.
Submitted by Amit Gandhi on Thu, 06/05/2014 - 08:56Permalink
dir /b /a-d-h-s > list.txt
Submitted by Ray on Sun, 08/03/2014 - 15:45Permalink
Add new comment