Complete Batch Programming Chapter 2 | Learn Batch Commands

We will write Batch Commands in batch programming It is the native programming offered by the Microsoft Windows Operating System. Batch file is created using any text editors like WordPadNotepadWinWord or so on, which comprises of a sequence of built-in commands used to perform some often done tasks like deleting a series of files of same type or of different type, creating logs, clearing unwanted craps  from your computer and even for creating a batch VIRUS and much more uses of batch programming. Whenever a Batch program is executed, it was interpreted line-by-line by the CLI (Command Line Interpreter) command.com or the cmd.exe. Batch file is really helpful in automating tedious tasks and for maintaining system logs. The commands used while creating a batch file are case insensitive, in the sense that it may accept both small and upper case letters.
It is first part of our batch programming series.
Click here for first part: Part-1


Environment Variables

 Environment variables are special variables that contain its values set by the operating system itself, other applications or by manual. Environment variables are set to reduce tasks and code complexity by calling them in program, since they are just placeholders that keeps track of the system properties and system wide changes, and then sets its value. It holds values like drive path, currently logged in username, root drive, Operating System name and version and so on

The following are the few environment variables set in Windows XP,


Environment Variables                         Description
%ALLUSERSPROFILE%                   C:\Documents and Settings\All Users
%APPDATA%                                      C:\Documents and Settings\{username}\Application Data
%CD%                                                  Current working directory
%CMDCMDLINE%                            Displays Windows Version
%CMDEXTVERSION%                     Command prompt version
%COMPUTERNAME%                      Equivalent to hostname command
%COMSPEC%                                     C:\Windows\System32\cmd.exe
%DATE%                                              Display current date
%ERRORLEVEL%                              Exit code for the previously executed command
%HOMEDRIVE%                                Root Drive
%HOMEPATH% \                                Documents and Settings\{username}
%NUMBER_OF_PROCESSORS%    Displays number of processors
%OS%                                                  Displays the name of the OS installed
%PATH% Points to                               C:\WINDOWS\system32
%PATHEXT%                                      .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS ; .WSF;
%PROCESSOR_ARCHITECTURE%  Displays the processor architecture
%PROCESSOR_LEVEL%                    Displays the processor level
%PROCESSOR_REVISION%              Displays the processor revision
%PROMPT%                                          Displays the current prompt
%RANDOM%                                        Generates a random integer between 0 and 32767
%SYSTEMDRIVE%                              Moves to the Root drive
%SYSTEMROOT%                               C:\WINDOWS
%TEMP% and %TMP%                         C:\DOCUME~1\{USER}\LOCALS~1\Temp
%TIME%                                                 Displays current time
%USERDOMAIN%                                Displays the hostname
%USERNAME%                                     Displays the currently logged in user name
%USERPROFILE%                                 C:\Documents
%WINDIR%                                             C:\WINDOWS

You can manually set an environment variable using the ‘SET’ command and those variables set by this command will not reside permanently in the system but they were temporary and will be lost after a reboot.

To set an environment variable manually by using ‘set’ command,
C:\>set C=C:\windows\system32\cmd.exe
C:\>%C%   
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

In the above example, I have set an environment variable name ‘C’ and assigned the value the path to the command prompt. Then value can be accessed by using % on both sides of the variable like ‘%c%’. Since I have set the path to the command prompt to the variable ‘c’, when the variable is accessed, it will open up a new command prompt in the existing window.

Note: - Every Operating system does have its own environment variables.

Looping statement

Likewise other programming languages, batch file programming does support looping with the help of got statements and for statement. Since we have already learnt about the ‘goto’ statement, we are going to see how the ‘for’ statement works.

Like many other command, the ‘for’ statement do have its own switches for operating in various ways.

The commonly used switches are,

For /D                     The '/D' switch along with the ‘for’ command is used for looping through Several                                 directories

For /R                     The '/R' switch along with the ‘for’ command is used for looping through                                              Directories and sub directories.

For /L                      The '/L' switch along with the ‘for’ command is used for looping through a range                                  of specified numbers.

For /F                       The ‘/F’ switch along with the ‘for’ command is used for looping through a                                           wide variety of files, command and strings.

In addition, substitution of FOR variable references has been enhanced.

You can now use the following optional syntax:

%~I             expands %I removing any surrounding quotes (")
%~fI            expands %I to a fully qualified path name
%~dI           expands %I to a drive letter only
 %~pI          expands %I to a path only
 %~nI          expands %I to a file name only
 %~xI          expands %I to a file extension only
 %~sI          expanded path contains short names only
 %~aI          expands %I to file attributes of file
 %~tI           expands %I to date/time of file
 %~zI          expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string.

The modifiers can be combined to get compound results:

%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH 

environment variable for %I and expands to the
drive letter and path of the first one found.
 %~ftzaI - expands %I to a DIR like output line

Here I am going to cover all kinds of usage of the ‘for’ command along with some code snippets,
FOR /D %v IN (*.*) DO dir/s "%v"  
As said earlier, that the ‘/D’ switch along with the ‘for’ command is used for looping through the directories and sub-directories. The above given command is used for displaying all the directories and sub directories.

Note: When you execute this command right from the command prompt by copying it and pasting it will work, but when you create a batch file using this code, won’t work, because when you are using it in a batch file, you are supposed to use %% preceding the variable name, in this case the following code will work if you try to execute as a batch,
FOR /D %%v IN (*.*) DO dir/s "%%v"
The ‘/R’ switch when used with the ‘for’ command is used for looping through Directories and sub directories.
FOR /R C:\Windows\Prefetch %v IN (*.pf) DO del %v  
The above piece of code is used for deleting prefetch files from the location C:\windows\prefetch, which are considered to be unnecessary and which hogs up the memory.

The ‘/L’ switch when used with the ‘for’ statement is used for looping through a wide variety of specified numbers. In the below example, I have enclosed a snippet that I used for finding open port and if an open port is found, then it will telnet to it and establish a remote connection, but the user has to supply the IP address or the hostname as parameter to this program, only then it becomes effective.
for /L %%v in (1,1,20) do telnet %1 %%v  
If you notice the set (1,1,20) that contains 1,1,20, where the ‘1’ in the front denotes the initial value for the loop, the second ‘1’ denotes the increment value or the step value, since it is stated as ‘1’ over here, the loop will be incremented by one and finally the ‘20’ denotes the end value, indicating that the loop was supposed to be terminated when the count reaches 20.

The following piece of code will help you to better understand how it works,
FOR /L %G IN (20,-2,0) DO ECHO %G  
If you notice the set, it has some negative values too which in turn describes that we can use negative integers too while looping using the ‘for’ statement.

The ‘/F’ is a special switch where it has a set of extra options available for it, which includes the following,

eol=c -                  specifies an end of line comment character (just one)
skip=n -                specifies the number of lines to skip at the beginning of the file.
delims=xxx -        specifies a delimiter set. This replaces the default delimiter set of space and tab.
tokens=x,y,m-n -  specifies which tokens from each line are to be passed to the for body for each                                     iteration. This will cause additional variable names to be allocated. The m-n form
                             is a range, specifying the mth through the nth tokens. If the last character in                                           the tokens= string is an asterisk, then an additional variable is allocated                                                 and receives the remaining text on the line after the last token parsed.
usebackq -            specifies that the new semantics are in force, where a back quoted string is                                           executed as a command and a single quoted string is a literal string command and                                 allows the use of double quotes to quote file names in filenameset.

The following statement is used for listing all the directories and files available inside the C:\a directory,

FOR /F "tokens=*" %v IN ('dir/b ^"c:\a^"') DO ECHO %v  
The statement given below is used for displaying all the processes running in the background. It just uses the ‘tasklist’ command inside the ‘for’ loop to display them.
FOR /F "delims==" %v IN ('tasklist') DO @ ECHO %v 
The following statement helps you in better understanding of the token and the delimiters used with the ‘/F’ switch,
FOR /F "tokens=1,3* delims=," %v IN ("Complete,Batch,Programming") DO @ ECHO %v wrote %w 
The tokens specify the string or command that reside inside the set, here the tokens used were 1 and 3, which is namely the ‘Complete,Batch,Programming’, this clearly states that each token has a index value starting from the integer 1 and goes on like that.

The ‘delims’ is short for the delimiters, in this case, they were just the separators used in between each string or command that reside inside the set in order to separate them. In this scenario, the comma is the delimiter used.

The statement will fetch the token 1 ‘Cyber’ and token 3 ‘E-book’ and echoes the string ‘wrote’ in between them, thereby creating the output ‘Cyber wrote E-Book’.

Likewise the ‘for’ statement can be used in various other ways extending the features of the batch file programming.

Conditional Statements

The conditional statement enriches the features of the batch file programming. The conditional statements are widely used for making a decision, and in accordance to the decision taken, the result or the output is produced.

The primary decision making statements used in batch programs are,
IF and IF NOT.  
The decision making statements deals with error levels, string matching and files.

The following piece of code will help you in a better understanding of how it deals with files and folders,
@echo off
if exist C:\windows. (
echo Found
) else (
echo Not found
)
Pause
In this case, the program will check for the directory C:\windows, and if it exists then it will display the message ‘Found’ else it will display ‘Not Found’.

The following piece of code is used for dealing with the error level generated by the ‘tasklist’ command. The ‘tasklist’ command, in case of successful execution will return the error level as ‘0’ and in case of failure in the execution it will return ‘1’.
@echo off
tasklist
cls
if errorlevel 1 (
echo success
) else (
echo Failed
)
Pause
The result of this program would be either ‘success’ or ‘Failed’ , depending upon the error level generated by the ‘tasklist’ command, if the error level is ‘0’ then the result will be ‘Success’ else if the error level is ‘1’ then the result will be ‘Failed’.

The following piece of code shows how the decision making statements, takes a decision on comparing a string,
@echo off
:begin
color a
echo Access Code :
set /p ac=
if %ac%==12345 (
echo Access Granted
) else (
echo Access Denied
goto begin
)
Pause  
This code, when executed will prompt the user to enter the access code, if the access code entered matches 12345, then it will display ‘Access Granted’ else it will display ‘Access Denied’.

The below code snippet reveals the usage of ‘IF NOT’ statement,
@echo off
color a
if not exist "c:\Program Files\Mozilla Firefox" (
echo Firefox is not yet installed , please Install it now
) else (
echo Firefox is currently installed
)
Pause 
This program will check whether the Mozilla firefox is currently installed on the computer, if not detected, then it will display “Firefox is not yet installed , please Install it now”, and if it detects that Mozilla is installed then it will display “Firefox is currently installed”

Similar to the operators we use in the batch programs, we may also use the following comparison operators in string form,

OPERATORS              MEANING
EQU                             EQUAL
NEQ                             NOT EQUAL
LSS                               LESS THAN
LEQ                              LESS THAN OR EQUAL
GTR                             GREATER THAN
GEQ                             GREATER THAN OR EQUAL 

Commands associated with files and folders

This chapter will cover all the commands associated with the files and folder for performing operations such as creating a new file, folder, renaming it, displaying it, copying it, moving it and deleting it.

Dir:

The ‘dir’ command is used to display the contents in a directory. Likewise other commands, this too have few switches available to narrowing down the result i.e. displaying the file in various other ways than that of the usual way.

When the ‘dir’ command is used alone without any switches, it will display the contents of the current directory.

I have executed the ‘dir’ command in my C: drive, and it displayed the files and folders available in the C drive. The

indicates that it is a folder or a Directory, where as the rest of them are just file, even the file extensions are displayed at the end of the file name, so that it is easy to identify what kind of file it is and also displays the size of the file and free memory space available on the drive.

Every directory will have any one of the attribute set, the commonly used attributes are Readonly, Directory, Hidden files, Archived file, system file, indexed and so on. By default the ‘dir’ command wont display the system files, sometimes you have to revoke the read-only permission to modify a file, to maintain a little bit of privacy you may also have to hide a directory, all these can be done with the help of the ‘/A’ switch along with the ‘dir’ command. When the ‘dir /a’ command is executed, it will display all the files and folders in a directory, no matter what attribute is set. The ‘dir /a’ can be optimized completely by using few parameters available for the ‘/a’ switch, which is very useful in narrowing down the result that we are looking for.

The ‘dir /a’ command alone will display all kinds of files, directories and sub-directories that reside in the current directory.

If you notice, which is nothing but a folder which is common for all the users, and where their documents reside.

Further if we want to narrow down the result, we can use the following available parameters for the/aswitch, they were,

D’ for Directories, ‘R’ for Read-only files, ‘H’ for Hidden files, ‘A’ for Files ready for archiving, ‘S’ for System files and ‘I’ for Not content indexed files.

If I want to view all the files hidden by the user alone, then I can use the command ‘dir /ah’, likewise if I want to view all the read-only files then I have to use the command ‘dir /ar’ and so on.

The ‘dir /b’ command is used to perform the operation similar to the ‘dir’ command, but it will display bare information i.e. the directory name alone, which doesn’t contain any further info such as the file size, date, file and free space available.

This format doesn’t even have any kind of header information.

The ‘dir’ command by default will include the separators between the integers while displaying the file sizes, the ‘/c’ switch when used with the ‘dir’ command will perform the same operation. To avoid the ‘dir’ command displaying the separator in between the integers while displaying the file sizes, you may use the ‘/-c’ switch for revoking separator.

we have to use the ‘dir /TA’ command, likewise to know when a file was last modified, then we have to use the ‘dir /TW’ command.

The ‘dir /w’ command is used for displaying the same in a wide list

The ‘dir /x’ command is used to display short names for a non-8dot3 file names. If you are not aware of the non08dot3 files, here is an example,’ Program Files’ is a non8dot3 file, where it can be shortly written by the OS as ‘PROGRA~1’

Here is another crap done by Microsoft, that ‘dir’ command by default will display the date in a four digit year, but there is an additional switch ‘dir /4’ which is used to display four digit year, I don’t know whether it has something to deal with the Y2K bug or something like that.

Mkdir:

The ‘mkdir’ command is short for the make directory, which in turn is used to create new directories in the specified location also the ‘mkdir’ command is a replacement of the ‘md’ command. We can create multiple directories just by using a single ‘mkdir’ command.

If I wish to create a new directory named ‘pictures’, then I can use the command ‘mkdir pictures’ , if there is a space in between the folder name then we can use the Double quotes surrounded by the directory name that contains the space in between them, for example if I want to create a directory name ‘My Collections’, then I can use the use the command ‘mkdir “My Collections”’.

If I wish to create 3 different directories that reside one into one, namely ‘a’,’b’ and ‘c’ then I can use the command ‘mkdir a\b\c’, where as the directory ‘b’ resides inside ‘a’ and ‘c’ resides inside ‘b’.

Rmdir:

The ‘rmdir’ command is short for the remove directory, which in turn is used to purge already existing directories, the ‘rmdir’ command is a replacement of the ‘rd’ command. Unlike the ‘md’ command, the ‘rd’ command has two switches, where the ‘/s’ switch is used to delete all the directories, sub-directories and files inside the specified directory. The ‘/Q’ switch is used to remove a folder in quiet mode, so that whenever you delete a folder it won’t prompt you for the confirmation whether to delete the directory or not.

Chdir:

The ‘chdir’ command is short for change directory, which is a replacement command for the ‘cd’ command, more over this is the only command the doesn’t require any quotes even when there is a space in between the directory names, because it won’t treat space as delimiters. For example, 
cd \winnt\profiles\username\programs\start menu 
for the above path, there is a space between the ‘start menu’, where as we have to enclose it within quotes when we use the same with some other commands like this,
cd "\winnt\profiles\username\programs\start menu"  
 but this is not a case with the ‘cd’ command.

Ren:

The ‘ren’ command is short for the rename, and it’s the replacement for the ‘rename’ command, the command name itself implies that this command is used for renaming a file or a directory. We are supposed to ensure that we are including the file extension while renaming a file, but this is not a case with directories.

For example, if I wish to rename a directory from ‘admin’ to ‘administrator’, then I can use the command,
C:\>Rename admin administrator

Replace:

The operation of the ‘replace’ command is similar to the copy [CTRL+C] and paste [CTRL+V] operation, for example, there exists a directory named ‘a’ which contains a text file with name ‘a.txt’, when the below command is used, the file ‘a.txt’ from the directory ‘a’ is moved to the directory ‘b’,

The ‘/P’ switch will prompt for confirmation whether to replace a file or adding to a source file. The ‘/R’ switch is used even for replacing read-only files as well as unprotected files. The ‘/S’ switch is used for replacing files even in all the sub-directories, and this switch must not be used along with the ‘/A’ switch.. The ‘/W’ switch is wait for the user until he/she inserts a new disk before beginning. The ‘/U’ is a kind of update, where as it appends to an existing file if found older.

Copy:

The name of the command ‘copy’ itself implies that it is used for copying one or more files from one location to another specified destination location. Two primary things namely the source and the destination files are required to make the copy operation complete and successful. The ‘copy’ command works only with files but not on directories, even though a directory name is mentioned, it will copy the contents from the source directory to the destination directory.

For example, I have mentioned the directory names both ‘a’ and ‘b’, but if you notice the line below that, it says the ‘C:\a\a.txt’, so ‘a.txt’ is a file that resides inside directory ‘a’ and which is been copied to the destination directory ‘b’. 

Likewise other command, ‘copy’ command does have its own set of switches. The ‘/A’ switch is used to copy files in ASCII mode, where as the ‘/B’ switch is used to copy files in Binary mode, the ‘/D’ switch is used to make the destination folder decrypted, the ‘/V’ switch is used for verifying whether the files have been written correctly, the ‘/N’ switch is used for creating short file names which usually is not a 8dot3 name. Sometimes when you copy a file from source to destination, and if found that the destination contains the file already, then it will try to overwrite the existing file prompting you whether to do so, and works according to the users choice, the ‘/Y’ switch is used to overcome this, and if this is used then it will suppress prompting for confirmation, where as the ‘/-Y’ is mere opposite to the ‘/Y’ which makes the command to prompt for confirmation for proceeding further. The ‘/Z’ switch is used to copy networked files.

Xcopy: 

‘Xcopy’ is a superset of the ‘copy’ command, with few additional features like copying directories, directory structure, exclusion of specified file copying, copying files that are modified on or after specified date, exclude copying empty directories and so on. The ‘Xopy’ command does have lot of switches extending the features of the copy command.

The ‘/A’ when used with the xcopy command is used to copy files with the archive attribute set without changing the attribute, where as the ‘/M’ switch does the operation similar to the ‘/A’ switch but won’t modify the attribute from archive.

The ‘/D’ provides a user friendly option, which is used to copy files which are modified on or after the specified date. The ‘/D’ switch has parameters for accepting month, day and year, which in turn can be represented in the ‘/D:m-d-y’ format. If no date is specified then it will copy the files whose source time is newer than the destination time.

The ‘/Exclude’ switch is used for restricted copying, so that we can restrict or avoid copying few specified type of file. You can restrict either the type of file or by using the string, for example, if I want to avoid copying bitmap files, then I may use the below command,
C:\>xcopy /exclude:.bmp Images IMG 
When the above command is executed, it will copy all kind of files from the directory ‘Images’ to ‘IMG’ except the bitmap files.

The ‘/P’ switch will prompt you whether to create the destination file or not. The ‘/S’ switch copies all the directories and sub-directories except the empty ones, where the ‘/E’ switch is mere opposite to the ‘/P’ and is used to copy even the empty directories.

Similar to the copy command, the ‘/V’ switch is used to verify whether the files are copied correctly. The ‘/W’ switch will force to press a key by prompting you to copy files. The ‘/C’ switch will continue copying files even if an error occur.

The following were the exit codes for the xcopy command,

Exit code          Description
0                       Files were copied without error.
1                       No files were found to copy.
2                       The user pressed Ctrl+C to terminate xcopy.
4                       Various errors including insufficient memory or disk space, an invalid                               drive name, or invalid syntax.
5                       Disk write error occurred. 
If you are copying more than one file, where the destination doesn’t exists and when used the ‘/I’ switch it will assume that the destination must be a directory and copies files.

The ‘/Q’ switch will not display file names while copying, the ‘/F’ switch displays the complete source and the destination names while coping, the ‘/L’ is used for displaying files that are supposed to be copied.

The ‘/G’ switch allows copying of encrypted files to destination that doesn’t support encryption. The ‘/H’ switch is used even for copying files that are set with hidden and system file attribute. The ‘/R’ switch when used is used to overwrite the read-only files, this switch really helps in modifying the autorun.inf virus source by forcing to write to a read-only file.

The ‘/T’ switch is used for creating a directory structure, but it won’t copy files and also won’t include any empty directories in the directory structure.

The ‘/U’ switch is used for copying files that already reside in the destination directory.

Whenever you copy a file using the ‘xcopy’ command, it will reset the file attributes, the ‘/K’ switch is used to copy the attributes along with the file content, so that the attributes remains the same after copying. The ‘/N’ copies file even if the short names (8dot3) that we have seen already.

The ‘/O’ switch copies the file ownership and the Access Control List Information, so that the security remains the same if it is copied inside the same HDD. The ‘/X’ switch is similar to the ‘/O’ switch but also copies the audit settings.

The ‘/Y’, ‘/-Y’ and ‘/Z’ switches were the same as we already seen in the copy command. The ‘/B’ switch copies the symbolic link instead of copying the source itself. (Symbolic link is nothing but the shortcut).

Del:

The command ‘del’ from that name by itself implies that it is used for deleting files but not directories and it is the replacement of the ‘erase’ command. If you want to delete a list of files that reside inside a directory, there is no need for specifying the filename one by one, just the directory name will do, for example, if I wish to purge all the files that reside inside the directory ‘junk’

Once the command is executed, then it will prompt you to confirm whether or not to delete those files. So the above command will delete all the files that reside inside the directory ‘junk’.

By default the ‘del’ command, when you are attempting to delete some files will prompt you whether to delete the files or not, if not then you may use the ‘/P’ switch to force prompting the same. The ‘/F’ switch is used to force deleting the read-only files. The ‘/S’ switch is used to delete all the specified files even from the sub-directories. The ‘/Q’ switch when used will not prompt for the confirmation to delete files and is also called quiet mode.

You may also specify the file attributes to delete, using the ‘/A’ switch, since we have to specify the type of attribute there are few available parameters indicating the attribute, ‘R’ for Read-only files, ‘S’ for System files, ‘H’ for Hidden files, ‘A’ for Files ready for archiving, ‘I’ for Not content indexed Files, when these parameters are prefixed with the ‘-‘ hyphen will ignore the specified attribute.

Pushd:

 The ‘pushd’ command is used to push the current working directory or the specified directory in the stack and remembers it until it gets popped out. For example, if I want push ‘C:\windows\system32’ into the stack using the ‘pushd’

After Using This Command if you notice, when the command gets executes, it not only remembers the path, but also changes the path to the specified directory.

Popd:

The ‘popd’ command is used to pop out from the directory that is pushed using the ‘pushd’ command. Likewise the ‘pushd’ command, it not only purges the stack, but also moves back to the directory in which the ‘pushd’ pushed the directory

‘pushd’ command pushes the ‘C:\windows\system32’ into the stack and changes the directory to the ‘system32’, when the ‘popd’ command gets executed, it purges the stack and pops out from the ‘system32’ directory to ‘C:\’.

Move:

 The ‘move’ command is similar to the ‘cut’ [CTRL+X] operation, which will completely moves the specified file from source to destination without leaving a copy in the source directory.

 A text file ‘a.txt’ is moved from the source ‘C:\a’ to the destination ‘C:\b’. The ‘/y’ switch when used with the ‘move’ command will not prompt you for confirming to proceed with the action, where as you can set the option by using the ‘/-y’ switch.




Post a Comment

0 Comments