Friday, November 18, 2011

Batch Files: getting started part III

Now lets try to modify the first example a bit...i.e. make it more cooler, so this modified batch file example is going to list all the files in a folder and put the list in a new text file . We will use the directory command "dir" that you are already familiar with.
Open Notepad and enter the line "@echo off" (without quotes).
Next enter another line dir "C:\Program Files" > C:\list_of_program_files.txt(I'm assuming that your Program Files folder is on the C: drive). This will give us the two-line file @echo offdir "C:\Program Files" > C:\list_of_program_files.txt
 Now save this two-line file as "listprograms.bat" (without quotes) to some convenient location. Be sure that Notepad is saving as "All files" and not as a text file

  • Note that complete paths are used for files including the drive letter, even the files' extension is specified. 
  • Also note the quotes around "C:\Program Files". Paths must be quoted whenever a file or folder name has a space in it. Finally note the redirection symbol ">" that is used to send the output to a file instead of the screen.
All that has to be done to use the file is to double-click it. A file C:\list_of_program_files.txt will then be created.

The file above is limited to listing one particular folder and putting the list in one particular file. However, it is easy to make the file able to list whatever folder we want and to put the list wherever we want(it is also much cooler and professional).
Batch files can use arguments or data inputted by the user. The process makes use of placeholders of the form %1, %2,
These are replaced in the script by our input data. This type of situation cannot be clicked directly but should be run in a command prompt. The new batch file would be 
@echo offdir %1 > %2
Enter in Notepad and save as "vari_list.bat". To run the file, open a command prompt and enter{path}vari_list somefolder somewhere\list.txt
where somefolder is whatever folder (with complete path) that you want to list in somewhere\list.txt. Now you have created a little batch script(program) that will list the contents of a folder whenever you want. If you want to extend the listing to include a list of all the subfolders as well, use the command dir /s %1 > %2 
If you want a list that only includes files of a certain type i.e. to filter a particular type of file based on its extension, MP3 files for example, use dir %1\*.mp3 > %2
The line above illustrates the use of the asterisk "*"  before the file extension is specified, known as a  wildcard in DOS. The ability to use wildcards greatly enhances the power of batch files
You can play with the above file by trying different parameters (folder paths) for the batch file and observing the results.....

Continues in part 4 ....... stay tuned .....

No comments:

Post a Comment