Saturday, 5 October 2013

Operator precedence

  Likewise other programming languages, batch program does support operator precedence for performing a valid arithmetic operation to obtain accurate results. The precedence of operations are given in order, *, /, %, +, -. The expression that is enclosed and grouped with the grouping operator ‘()’ gets the high priority in the precedence.

C:\>set /A (10-5)*2+6/2

In the above example, the expression that is enclosed within the ‘()’ operator gets the high priority and thus 10-5 is ‘5’, the next priority moves to the ‘/’ division operator and ‘6/2’ gives ‘3’, then comes the multiplication ‘*’ operator 5*2 gives ‘10’ then it is summed up with ‘3’ to obtain the final result as ‘13’. To redirect the output of one command to other file, the ‘>’ and ‘<’ command is used. For example the below command is used to print the text “hello redirection” to a notepad file named “first.txt”

C:\>echo hello redirection > first.txt C:\>

As we already have seen that the ‘echo’ command is used for printing the given text on the screen, here by using the redirection operator ‘>’ we are redirecting the output of the command to a text file. It will create a new text file even it wasn’t already there. Likewise you can redirect the output of any command to any other files. The below command is used for performing the same operation but the redirection happens to word document,

C:\> echo hello redirection > first.doc

The tilde ‘~’ operator is a unary operator that is used for shortening the long directory names, the following example will brief with the usage of this operator. The tilde operator can be used after 6 consecutive characters of a directory name, for example the “Documents and Settings” is a directory that contains more than 8 characters, instead of typing them all and messing with it, we can use the ‘~’ operator, so that it will automatically recognizes the path and performs the operation mentioned,

C:\>cd C:\DOCUME~1\CYB3RC~1\LOCALS~1\Temp C:\DOCUME~1\CYB3RC~1\LOCALS~1\Temp>

The above command is just a path to the location “C:\Documents and Settings\Cyb3rcr4wl3r\Local Settings\Temp”, where “Cyb3rcr4wl3r’ is the user account on my computer. Note: even though the ‘~’ operator is a unary operator, it can’t be used without the 1 following the operator. The ‘&&’ operator is used to execute multiple commands in a single line, for example, the following command is used to print the text ‘hi’ and ‘hello’ using two different echo commands,

C:\>echo Hi && echo hello Hi Hello

The pipeline operator is used for giving the output of one command as input for another command, C:\>echo Y | del *.txt

In the above example, whenever you delete a file using the del command, it will prompt you with a confirmation message whether to delete the file or not, and only depending upon the user input it will proceed further, here we can make use of the pipeline ‘|’ operator to print ‘Y’ when the ‘del’ command prompt for the user interaction. Whenever the ‘del’ command prompts the user for the confirmation, the output of the echo command (i.e. ‘Y’) will be given as input for the del command, and as a result it deletes all the text files that reside in the specified directory.

Batch Operators

Similar to other programming languages, batch program do support various operators for performing operations like arithmetic and logical operations, bitwise AND, OR, NOT, shifting and redirection operation and separators and grouping operators. Operators-Description

()-Grouping ! ~ -   Unary operators * / % + -       Arithmetic operators << >> < >  Logical shift and redirectional operators
& Bitwise and
^ Bitwise exclusive or |-Bitwise or = *= /= %= += -= &= ^= |= <<= >>=  Assignment operators
, - separator
&&  For using Multiple commands ||  For executing one from many commands

The above given were the operators available in Batch file programming for performing arithmetic and

logical operations. Let me brief you the operators with a small example, Note : For performing arithmetic operations, the ‘SET’ command should be used along with the ‘/A’ switch. For performing an addition operation on two integers, then I have to use the below command,
C:\>set /A 5 + 5
10

As you see in the above example, the ‘set /A’ is used for performing arithmetic operations like addition, subtraction, multiplication and division. The above example is used for performing an addition operation on two integer namely 5 and 5 and gives the output as ‘10’. Similarly you can use the other arithmetic operators.

Example:
The below command is used to subtract 5 from 10.
C:\>set /A 10-5
5
The below command is used finding the product between 5 and 5.
C:\>set /A 5*5
25
The below command is for dividing 10 by 5 and displays the output.
C:\>set /A 10/5
2
The below command is finding the remainder value and this operator is called modulo operator. In this example the remainder value obtained when 11 divided by 5 is 1 and is displayed as output.

C:\>set /A 11%5
1

Internal and External Commands

   There are two types of commands that we can run from a command prompt, and they were,

1. Internal commands 2. External commands.

Internal Commands

Internal commands are nothing but the built-in commands that are shipped along with the operating system, for example, echo, cls, del, dir were few of the well known internal commands.

External Commands

External commands are the commands that are often created while installing a new application and these commands mostly have no use except calling that application and support files. Few external

commands can only be executed in the ‘Run’ dialog box (start ? Run), but not on the command prompt,and those commands include ‘firefox’. The ‘firefox’ command can be executed only from the run line, that too if the firefox application is installed on that machine and it won’t work on the command prompt. Likewise the ‘firefox’ there are various other external commands such as the “PsTools” which includes commands like, PsExec, PsFile, PsGetSid, PsInfo, PsKill, PsList, PsLoggedOn and so on.

Run Line commands

As said earlier batch file is comprised of sequence of run line commands, hence it’s a must to know at least few useful run line commands for constructing a good batch program. Here I am going to

list out the useful run line commands with a brief description. Commands-Descriptions

access.cpl-Accessibility Controls accwiz-Accessibility Wizard appwiz.cpl-Add/Remove Programs ciadv.msc-Indexing Service control-admintools Administrative Tools cleanmgr-Disk Cleanup Utility control-color Display Properties compmgmt.msc-Computer Management Console control folders Folder Options cliconfg-SQL Client Configuration certmgr.msc- Certificate Manager charmap-Character Map chkdsk-Check Disk Utility clipbrd-Clipboard Viewer calc-Opens calculator cmd-Opens command prompt devmgmt.msc-Device Manager dfrg.msc-Disk Defragmenter diskmgmt.msc-Disk Management dcomcnfg-Component Services ddeshare-DDE Shares diskpart-Disk Partition Manager desk.cpl-Display Properties drwtsn32-Dr. Watson directx.cpl- Direct X Control Panel dxdiag-Direct X Troubleshooter eudcedit- Private Character Editor eventvwr.msc- Event Viewer ( Maintaining System Logs ) explorer-Opens My Documents freecell-FreeCell Game fsquirt-Bluetooth Transfer Wizard fsmgmt.msc-Shared Folders gpedit.msc-Group Policy Editor hdwwiz.cpl-Add Hardware Wizard iexpress-Iexpress Wizard (Package creator) iexplore-Internet Explorer inetcpl.cpl-Internet Explorer Properties ipconfig-Windows IP Configuration intl.cpl-Regional Settings joy.cpl-Game Controllers lusrmgr.msc-Local Users and Groups logoff-Logs out current user magnify-Open Magnifier makecab-Cabinet Maker, file compressor. msconfig-Open System Configuration Utility mshearts-Opens Hearts game msinfo32-System Information mspaint-Opens Mspaint msmsgs-Windows Messenger mstsc-Remote Desktop mmsys.cpl-Sounds and Audio mqbkup-Message Queue Backup\Restore Utility notepad-Opens a New Notepad ntmsmgr.msc-Removable Storage ntmsoprq.msc-Removable Storage Operator Requests ncpa.cpl-Network Connections netsetup.cpl-Network Setup Wizard openfiles-Used to view Files Opened Remotely via localshare points odbccp32.cpl-ODBC Data Source Administrator osk-On Screen Keyboard proxycfg-Proxy configuration packager-Object Packager perfmon.msc-Performance Monitor powercfg.cpl-Power Options pentnt-Checks for Floating point error in Intel based processors qappsrv-Displays the available application terminal servers on the network. qprocess-Displays information about processes qwinsta-Display information about Terminal Sessions rcp-Copies files to and from computer running the RCP service recover-Recovers readable information from a bad or defective disk. relog-Used for Logging. replace-Replaces files rexec-Runs commands on remote hosts running the REXEC-service route-Manipulates network routing tables rsh-Runs commands on remote hosts running the RSH service rsm-Manages media resources using Removable Storage runas-Allows a user to run specific tools and programs with different permissions than the user’s current logon provides. regedit-Opens Registry Editor rsop.msc-Resultant Set of Policy rwinsta-Reset the session rasphone-Remote Access Phonebookservices. msc-Used for Managing all the services on the computer. sigverif-File Signature Verification Tool secpol.msc-Local Security Settings shutdown-Shutdown Windows syskey-Windows System Security Tool sc-Communicates with the service controller and installed services. schtasks-Replaced with at. setver-Sets the version number that MS-DOS reports to a program shadow-Helps in remote connection & network used to monitor-another Terminal Services session shrpubw-Shared Folder Wizard sndvol32-Volume Control sysedit-Windows.ini, system.ini, config.sys, autoexec.bat sol-Opens up Solitaire Game timedate.cpl-Date and Time Properties telephon.cpl-Phone and Modem Options telnet-Telnet Client tftp-Transfers files to and from a remote computer running the TFTP service tlntadmn-Telnet Administration. Used to start, stop, and send msg-to a terminal session connected to via telnet. tscon-Attaches a user session to a terminal session. tsdiscon-Disconnects a session from a terminal server. tskill-Ends a process. Even can terminate a process running on a remote session. tourstart-Windows XP Tour Wizard tsshutdn-shutdown in 60 sec typeperf-Very useful in login events. Used to monitor Processor-threads and writes into a specified log file. userinit-My Documents verifier-Driver Verifier Utility winchat-Microsoft Chat winmine-Minesweeper Game wuaucpl.cpl-Automatic Updates wscui.cpl-Security Center wmplayer-Windows Media Player wmimgmt.msc-Windows Management Infrastructure w32tm-Tool used to diagnose problems occurring with Windows-Time. register to run as a service and add default configuration to the registry winmsd-System Information. wupdmgr-Windows Update Launches winver-Displays Windows Version write-Opens WordPad

How to create a Batch Program

As said earlier, batch programs can be written using any of the text editors such as notepad, wordpad and so on, but notepad is the most often used text editor in such cases. Like any other programing languages, lets start our first program with the ‘Hello World’ program.

1. Open up a notepad and type the following. @echo off Echo Hello World pause

2. Save the file with any name you wish, but make sure that you save the file extension with .bat, in this case I am saving this file as ‘first.bat’.

3. When you save the batch file, then the icon becomes like the below icon, In Windows XP, the Batch file icon looks like above, where as in Windows Vista the Icon looks like the below image,

4. Just double click to execute the batch file that you have created now. And the output looks like,

5. You are done!

Let me explain what does the above given program does, ‘echo’ is the command used to print text on the screen, so whatever that follows the echo command will be displayed on the output screen. This command is just like the ‘printf’ statement in the C language.

When you type the echo command alone, then it will tell you whether the ‘echo is ON’ or ‘echo is OFF’. It’s always recommended to turn the echo off, else it will display the prompts like (C:\>) and so on. In order to avoid the prompts being displayed, the echo is turned off by using the command “@echo off” or simply by using the “echo off”. “Echo Hello World” will display the “Hello World” on the output screen, and the pause command is used to wait for the user interaction, whether to proceed further or not. If the pause is not used, then the batch will terminate immediately after displaying the “Hello World”.

Introduction

        Batch file programming is the native programming offered by the Microsoft Windows Operating System. Batch file is created using any text editors like notepad, WordPad, WinWord 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. 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. Modes: There are two different modes that are supported by DOS (Disk Operating System), they were,

1. Interactive Mode.

2. Batch Mode (Silent Mode).

Interactive mode:

In interactive mode, when a command is executed, it interacts with the user for input and depending upon the input supplied by the user, the further processes are carried out. For example, let’s take the ‘del’ command. The ‘del’ command is used for deleting files that reside inside a directory. Now I am going to delete all the files inside a folder named ‘a’, and when I executed the following command, it is interacting with me prompting “Are you sure (Y/N)?”, confirming the deletion operation, and depending upon my input, it decides what to do. If I hit ‘Y’ then it will delete the files specified, else if I hit ‘N’ then it won’t delete.

C:\>del a C:\a\*, Are you sure (Y/N)? y

Batch Mode:

Batch mode can also be referred as ‘Silent mode’ or ‘Quiet Mode’, and this is mere opposite to the interactive mode. The command that operates at batch mode will never interact with the user at any instance, instead it will take care of every operation by itself. For example, I am going to explain this by using the same ‘del’ command. There is a switch available for the ‘del’ command, which makes the command to operate at silent mode, and that switch is ‘/Q’ C:\>del /Q a C:\> In this case, the command is not at all interacting with me, whether to delete those file or not. In the above example, I have tried to delete the same files in the same folder by using the same command but with a different switch. Anyhow both the commands will perform the same operation but the mode it operates differs.