Thursday, November 3, 2016

Essentials of Windows Batch File Scripting


Hello everyone,

In this post, I want to discuss/outline the essentials or must needed basics in windows batch scripting. This post helps to fashionably put the very first step in batch file script.

What is a batch file

A batch file contains a series of DOS commands, and generally used to automate frequently performed tasks.

Once created, we can simply double click the file and run the tasks. This improves the ease of execution and avoids repetitive coding which saves a lot of time over the long run..

Once we are familiar with basic concepts, writing a batch file is much simpler task.
 
The easiest way to create a batch file is to create a text file and change the extension to .bat
 
Variables

·         DOS does not require variable declaration.

Variable Assignment
·         Variables can be assigned values using the SET command
·         NOTE: Whitespace should not be used between the name and value while using the SET command.
·         For example, SET name = vishnu will not work but SET name=vishnu will work.

Display variable value
·         To display the value of the variable on the screen, %% has to be used like in ECHO %timeperiod%
·         Dynamic variables – These variable names are not visible using SET command. Rather, they are made available for reading using the % notation. To find out about them, type "help set".

Variable Name
Replacement Value Used
 %CD%
The current directory, not ending in a slash character if it is not in the root directory of the current drive
 %TIME%
The system time in HH:MM:SS.mm format.
 %DATE%
The system date in a format specific to localization.
 %RANDOM%
A generated pseudo-random number between 0 and 32767.
 %ERRORLEVEL%
The error level returned by the last executed command, or by the last called batch script.
 %CMDEXTVERSION%
The version number of the Command Processor Extensions currently used by cmd.exe.
 %CMDCMDLINE%
The content of the command line used when the current cmd.exe was started.

Variable Scope - Global and Local variables

·         By default variables are global to the command prompt session.
·         To set variables local to our script, use  SETLOCAL
·         The variables come out of local scope when issued ENDLOCAL command or calling EXIT  or when the execution reaches the end of file.

Escape Character

·         Carrot sign (^) acts as escape character for special characters.
·         Special character can also be escaped by enclosing the string in quotes(“). In this case, quotes are echoed as well.
·         In a batch file, you have to use a double percent sign (%%) to yield a single percent sign (%).

Standard Files

DOS uses the three universal “files” for keyboard input, printing text on the screen, and the printing errors on the screen. These standard files are also known as the standard streams.

The “Standard In” file, known as stdin, contains the input to the program/script.
The “Standard Out” file, known as stdout, is used to write output for display on the screen.
The “Standard Err” file, known as stderr, contains any error messages for display on the screen.

File Numbers  - Each of these three standard files are referenced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2

Redirection

Output
Most common task in batch files is sending the output of a program to a file.
The > operator sends, or redirects, stdout or stderr to another file. The > operator creates/overwrites a file while >> operator appends the output to the file.

For example, you can write a listing of the current directory to a text file.
DIR C:\MyOwnFiles\  >  C:\MyOwnFiles\Filelist.txt

If we observe closely, it is clear that the output of DIR C:\MyOwnFiles\ is redirected to the specified file instead of displaying on the screen.

Standard output and standard error can be sent to the same file through a single line of code using & prefix.
DIR C:\MyOwnFiles\  >  C:\MyOwnFiles\Filelist.txt   2>&1

Discard the output
We can discard the output of a command by redirecting it to a pseudo file called NUL
For example, The below commands gives the listing of a directory
DIR C:\MyOwnFiles\
Now, to discard the output, use the below commands
DIR C:\MyOwnFiles\ > NUL

Input
The < operator redirects the contents of a file to input to the program. Command prompt’s own stdin is called CON.
For example, if you want to sort and see the contents of the above file on screen, the below code works.
SORT < C:\MyOwnFiles\Filelist.txt

CTRL+Z sends the end-of-file (EOF) character in the batch code.

Return Codes – By default, if a command succeeds, the exit code is 0, on the other hand, if it fails, the exit code is 1.

Basic batch commands

In all through the discussion, we go with very basic and most frequently used commands.

·         ECHO - Displays text or output of a variable on the screen
o   ECHO %timeperiod%
·         @ECHO OFF - Hides the text that is normally output
·         START - Run a file with its default application
·         REM - Inserts a comment line in the program
·         CLS – Clear the screen
·         MKDIR/RMDIR - Create and remove directories
o   MKDIR D:\MyOwnDirectory
o   RMDIR D:\MyOwnDirectory
·         DEL - Deletes a file or files
·         COPY - Copy a file or files
·         XCOPY - Allows you to copy files with extra options
·         FOR/IN/DO - This command lets you specify files
·         TITLE - Edit the title of the window
·         /?  - Gives the help on any command
o   For example, for help on SET, use SET /?
·         /P  -  Prompt user for inputs
SET /p = [string]   i.e.   SET /p  name=Enter you name:  
·         SETLOCAL – To set the variables scope to local
·         ENDLOCAL - To end the variable scope to local. Thereon, any variable declared will be global
·         EXIT - To exit from the batch file execution

Comparison Operators

Operator
Meaning
EQU
equal to, also can use == double equal to
NEQ
not equal to
LSS
less than
LEQ
less than or equal to
GTR
greater than
GEQ
greater than or equal to

 Note: When comparing variables that are strings, it may be best to enclose the variable name in quotes. For example, if "%1" == somestring somecommand

Conditional Statements

Conditional branching with "IF" statements
IF (condition) (command1) ELSE (command2)
Also can check for negating condition using “IF NOT”
" IF EXIST" statement
IF EXIST somefile.ext DEL somefile.ext
You can also use a negative existence test:
IF NOT EXIST somefile.ext ECHO no file
" IF DEFINED" statement
Case is "IF DEFINED", which is used to test for the existence of a variable. For example:
if defined somevariable somecommand
This can also be used in the negative form, "if not defined"
" IF ERRORLEVEL" statement
IF ERRORLEVEL  n somecommand
"GOTO" command
IF (condition) GOTO :label
:label
...some other commands
The "End of File" (:EOF) label for exiting a script
IF (condition) GOTO :EOF

Switch
Switches specify the nature/behavior of the commands given.

For example, /A specifies that the command using it should perform arithmetic operations.
SET m=7*9
ECHO %m%
The output of the above code is 7*9

SET /A m=7*9
ECHO %m%
The output of the above code is 63



Switch
Description
/A
Copies only files with the archive attribute set, doesn't change the attribute.
/M
Copies only files with the archive attribute set, turns off the archive attribute.
Useful in backup.
/D:m-d-y
Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
Useful in backup.
/P
Prompts you before creating each destination file.
/S
Copies directories and subdirectories except empty ones.
/E
Copies directories and subdirectories, including empty ones. Same as /S /E.
May be used to modify /T.
/V
Verifies each new file. Not used by Windows XP.
/W
Prompts you to press a key before copying.
/C
Continues copying even if errors occur.
/I
If destination does not exist and copying more than
one file, assumes that destination must be a
directory.
/Q
Does not display file names while copying.
/F
Displays full source and destination file names while copying.
/L
Displays files that would be copied.
/G
Allows the copying of encrypted files to destination that does not
support encryption.
/H
Copies hidden and system files also.
/R
Overwrites read-only files.
/T
Creates directory structure, but does not copy files.
Does not include empty directories or subdirectories.
/U
Copies only files that already exist in destination.
/K
Copies attributes. Normal Xcopy will reset read-only
attributes.
/N
Copies using the generated "short" names.
May be necessary when copying from NTFS to FAT16.
/O
Copies file ownership and ACL information.
/X
Copies file audit settings (implies /O).
/Y
Suppresses prompting to confirm that you want to overwrite an existing
 destination file. May be preset in the COPYCMD environment variable
/-Y
Prompts to confirm you want to overwrite an existing destination file.
/Z
Copies over a network in restartable mode.
/EXCLUDE:file1[+file2][+file3]...
Specifies a list of files containing strings to be excluded. Tricky to use.






















































 
 
See you soon.

Thanks
SunilDutt N

No comments:

Post a Comment