Discuss Batch Script ”; Previous Next Batch Scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. Scripting is a way by which one can alleviate this necessity by automating these command sequences in order to make one’s life at the shell easier and more productive. This tutorial discusses the basic functionalities of Batch Script along with relevant examples for easy understanding. Print Page Previous Next Advertisements ”;
Category: batch Script
Batch Script – Network
Batch Script – Network ”; Previous Next Batch script has the facility to work with network settings. The NET command is used to update, fix, or view the network or network settings. This chapter looks at the different options available for the net command. S.No NET Commands & Description 1 NET ACCOUNTS View the current password & logon restrictions for the computer. 2 NET CONFIG Displays your current server or workgroup settings. 3 NET COMPUTER Adds or removes a computer attached to the windows domain controller. 4 NET USER This command can be used for the following View the details of a particular user account. 5 NET STOP/START This command is used to stop and start a particular service. 6 NET STATISTICS Display network statistics of the workstation or server. 7 NET USE Connects or disconnects your computer from a shared resource or displays information about your connections. Print Page Previous Next Advertisements ”;
Batch Script – Logging
Batch Script – Logging ”; Previous Next Logging in is possible in Batch Script by using the redirection command. Syntax test.bat > testlog.txt 2> testerrors.txt Example Create a file called test.bat and enter the following command in the file. net statistics /Server The above command has an error because the option to the net statistics command is given in the wrong way. Output If the command with the above test.bat file is run as test.bat > testlog.txt 2> testerrors.txt And you open the file testerrors.txt, you will see the following error. The option /SERVER is unknown. The syntax of this command is − NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506. If you open the file called testlog.txt, it will show you a log of what commands were executed. C:tp>net statistics /Server Print Page Previous Next Advertisements ”;
Batch Script – Debugging
Batch Script – Debugging ”; Previous Next Debugging a batch script becomes important when you are working on a big complex batch script. Following are the ways in which you can debug the batch file. Using echo command A very simple debug option is to make use of echo command in your batch script wherever possible. It will display the message in the command prompt and help you debug where things have gone wrong. Here is a simple example that displays even numbers based on the input given. The echo command is used to display the result and also if the input is not given. Similarly, the echo command can be used in place when you think that the error can happen. For example, if the input given is a negative number, less than 2, etc. Example @echo off if [%1] == [] ( echo input value not provided goto stop ) rem Display numbers for /l %%n in (2,2,%1) do ( echo %%n ) :stop pause Output C:>test.bat 10 2 4 6 8 10 22 Press any key to continue … Using pause command Another way is to pause the batch execution when there is an error. When the script is paused, the developer can fix the issue and restart the processing. In the example below, the batch script is paused as the input value is mandatory and not provided. Example @echo off if [%1] == [] ( echo input value not provided goto stop ) else ( echo “Valid value” ) :stop pause Output C:>test.bat input value not provided Press any key to continue.. Logging the error messages to another file It might get hard to debug the error just looking at a bunch of echo displayed on the command prompt. Another easy way out is to log those messages in another file and view it step by step to understand what went wrong. Here is an example, consider the following test.bat file: net statistics /Server The command given in the .bat file is wrong. Let us log the message and see what we get. Execute the following command in your command line: C:>test.bat > testlog.txt 2> testerrors.txt The file testerrors.txt will display the error messages as shown below: The option /SERVER is unknown. The syntax of this command is: NET STATISTICS [WORKSTATION | SERVER] More help is available by typing NET HELPMSG 3506. Looking at the above file the developer can fix the program and execute again. Using ErrorLevel to detect errors and log them Errorlevel returns 0 if the command executes successfully and 1 if it fails. Consider the following example: @echo off PING google.com if errorlevel 1 GOTO stop :stop echo Unable to connect to google.com pause During execution, you can see errors as well as logs: C:>test.bat > testlog.txt testlog.txt Pinging google.com [172.217.26.238] with 32 bytes of data: Reply from 172.217.26.238: bytes=32 time=160ms TTL=111 Reply from 172.217.26.238: bytes=32 time=82ms TTL=111 Reply from 172.217.26.238: bytes=32 time=121ms TTL=111 Reply from 172.217.26.238: bytes=32 time=108ms TTL=111 Ping statistics for 172.217.26.238: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 82ms, Maximum = 160ms, Average = 117ms Connected successfully Press any key to continue . . . In case of failure, you will see the following logs inside testlog.txt. Ping request could not find host google.com. Please check the name and try again. Unable to connect to google.com Press any key to continue . . . Print Page Previous Next Advertisements ”;
Batch Script – Process
Batch Script – Process ”; Previous Next In this chapter, we will discuss the various processes involved in Batch Script. Viewing the List of Running Processes In Batch Script, the TASKLIST command can be used to get the list of currently running processes within a system. Syntax TASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH] Following are the description of the options which can be presented to the TASKLIST command. S.No. Options & Description 1. /S system Specifies the remote system to connect to 2. /U [domain]user Specifies the user context under which the command should execute. 3. /P [password] Specifies the password for the given user context. Prompts for input if omitted. 4. /M [module] Lists all tasks currently using the given exe/dll name. If the module name is not specified all loaded modules are displayed. 5. /SVC Displays services hosted in each process. 6. /V Displays verbose task information. 7. /FI filter Displays a set of tasks that match a given criteria specified by the filter. 8. /FO format Specifies the output format. Valid values: “TABLE”, “LIST”, “CSV”. 9. /NH Specifies that the “Column Header” should not show in the output. Valid only for “TABLE” and “CSV” formats. Examples TASKLIST The above command will get the list of all the processes running on your local system. Following is a snapshot of the output which is rendered when the above command is run as it is. As you can see from the following output, not only do you get the various processes running on your system, you also get the memory usage of each process. Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ System Idle Process 0 Services 0 4 K System 4 Services 0 272 K smss.exe 344 Services 0 1,040 K csrss.exe 528 Services 0 3,892 K csrss.exe 612 Console 1 41,788 K wininit.exe 620 Services 0 3,528 K winlogon.exe 648 Console 1 5,884 K services.exe 712 Services 0 6,224 K lsass.exe 720 Services 0 9,712 K svchost.exe 788 Services 0 10,048 K svchost.exe 832 Services 0 7,696 K dwm.exe 916 Console 1 117,440 K nvvsvc.exe 932 Services 0 6,692 K nvxdsync.exe 968 Console 1 16,328 K nvvsvc.exe 976 Console 1 12,756 K svchost.exe 1012 Services 0 21,648 K svchost.exe 236 Services 0 33,864 K svchost.exe 480 Services 0 11,152 K svchost.exe 1028 Services 0 11,104 K svchost.exe 1048 Services 0 16,108 K wlanext.exe 1220 Services 0 12,560 K conhost.exe 1228 Services 0 2,588 K svchost.exe 1276 Services 0 13,888 K svchost.exe 1420 Services 0 13,488 K spoolsv.exe 1556 Services 0 9,340 K tasklist > process.txt The above command takes the output displayed by tasklist and saves it to the process.txt file. tasklist /fi “memusage gt 40000″ The above command will only fetch those processes whose memory is greater than 40MB. Following is a sample output that can be rendered. Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ dwm.exe 916 Console 1 127,912 K explorer.exe 2904 Console 1 125,868 K ServerManager.exe 1836 Console 1 59,796 K WINWORD.EXE 2456 Console 1 144,504 K chrome.exe 4892 Console 1 123,232 K chrome.exe 4976 Console 1 69,412 K chrome.exe 1724 Console 1 76,416 K chrome.exe 3992 Console 1 56,156 K chrome.exe 1168 Console 1 233,628 K chrome.exe 816 Console 1 66,808 K Killing a Particular Process Allows a user running Microsoft Windows XP professional, Windows 2003, or later to kill a task from a Windows command line by process id (PID) or image name. The command used for this purpose is the TASKILL command. Syntax TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F] Following are the description of the options which can be presented to the TASKKILL command. S.No. Options & Description 1. /S system Specifies the remote system to connect to 2. /U [domain]user Specifies the user context under which the command should execute. 3. /P [password] Specifies the password for the given user context. Prompts for input if omitted. 4. /FI FilterName Applies a filter to select a set of tasks. Allows “*” to be used. ex. imagename eq acme* See below filters for additional information and examples. 5. /PID processID Specifies the PID of the process to be terminated. Use TaskList to get the PID. 6. /IM ImageName Specifies the image name of the process to be terminated. Wildcard ”*” can be used to specify all tasks or image names. 7. /T Terminates the specified process and any child processes which were started by it. 8. /F Specifies to forcefully terminate the process(es). Examples taskkill /f /im notepad.exe The above command kills the open notepad task, if open. taskill /pid 9214 The above command kills a process which has a process of 9214. Starting a New Process DOS scripting also has the availability to start a new process altogether. This is achieved by using the START command. Syntax START “title” [/D path] [options] “command” [parameters] Wherein title − Text for the CMD window title bar (required.) path − Starting directory. command − The command, batch file or executable program to run. parameters − The parameters passed to the command. Following are the description of the options which can be presented to the START command. S.No. Options & Description 1. /MIN Start window Minimized 2. /MAX Start window maximized. 3. /LOW Use IDLE priority class. 4. /NORMAL Use NORMAL priority class. 5. /ABOVENORMAL Use ABOVENORMAL priority class. 6. /BELOWNORMAL Use BELOWNORMAL priority class. 7. /HIGH Use HIGH priority class. 8. /REALTIME Use REALTIME priority class. Examples START “Test Batch Script” /Min test.bat The above command will run the batch script test.bat in a new window. The windows will start in the minimized mode and also have the title of “Test Batch Script”. START “” “C:Program FilesMicrosoft OfficeWinword.exe” “D:testTESTA.txt” The above command will actually run Microsoft word in another process and then open the file TESTA.txt
Batch Script – Registry
Batch Script – Registry ”; Previous Next The Registry is one of the key elements on a windows system. It contains a lot of information on various aspects of the operating system. Almost all applications installed on a windows system interact with the registry in some form or the other. The Registry contains two basic elements: keys and values. Registry keys are container objects similar to folders. Registry values are non-container objects similar to files. Keys may contain values or further keys. Keys are referenced with a syntax similar to Windows” path names, using backslashes to indicate levels of hierarchy. This chapter looks at various functions such as querying values, adding, deleting and editing values from the registry. S.No Types of Registry & Description 1 Reading from the Registry Reading from the registry is done via the REG QUERY command. 2 Adding to the Registry Adding to the registry is done via the REG ADD command. 3 Deleting from the Registry Deleting from the registry is done via the REG DEL command. 4 Copying Registry Keys Copying from the registry is done via the REG COPY command. 5 Comparing Registry Keys Comparing registry keys is done via the REG COMPARE command. Print Page Previous Next Advertisements ”;
Batch Script – Functions
Batch Script – Functions ”; Previous Next A function is a set of statements organized together to perform a specific task. In batch scripts, a similar approach is adopted to group logical statements together to form a function. As like any other languages, functions in Batch Script follows the same procedure − Function Declaration − It tells the compiler about a function”s name, return type, and parameters. Function Definition − It provides the actual body of the function. Function Definition In Batch Script, a function is defined by using the label statement. When a function is newly defined, it may take one or several values as input ”parameters” to the function, process the functions in the main body, and pass back the values to the functions as output ”return types”. Every function has a function name, which describes the task that the function performs. To use a function, you “call” that function with its name and pass its input values (known as arguments) that matches the types of the function”s parameters. Following is the syntax of a simple function. :function_name Do_something EXIT /B 0 The function_name is the name given to the function which should have some meaning to match what the function actually does. The EXIT statement is used to ensure that the function exits properly. Following is an example of a simple function. Example :Display SET /A index=2 echo The value of index is %index% EXIT /B 0 S.No Functions & Description 1 Calling a Function A function is called in Batch Script by using the call command. 2 Functions with Parameters Functions can work with parameters by simply passing them when a call is made to the function. 3 Functions with Return Values Functions can work with return values by simply passing variables names 4 Local Variables in Functions Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function. 5 Recursive Functions The ability to completely encapsulate the body of a function by keeping variable changes local to the function and invisible to the caller. 6 File I/O In Batch Script, it is possible to perform the normal file I/O operations that would be expected in any programming language. 7 Creating Files The creation of a new file is done with the help of the redirection filter >. This filter can be used to redirect any output to a file. 8 Writing to Files Content writing to files is also done with the help of the redirection filter >. This filter can be used to redirect any output to a file. 9 Appending to Files Content writing to files is also done with the help of the double redirection filter >>. This filter can be used to append any output to a file. 10 Reading from Files Reading of files in a batch script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. 11 Deleting Files For deleting files, Batch Script provides the DEL command. 12 Renaming Files For renaming files, Batch Script provides the REN or RENAME command. 13 Moving Files For moving files, Batch Script provides the MOVE command. 14 Batch Files – Pipes The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command. 15 Batch Files – Inputs When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing. 16 Using the SHIFT Operator One of the limitations of command line arguments is that it can accept only arguments till %9. Let’s take an example of this limitation. 17 Folders In Batch Script, it is possible to perform the normal folder based operations that would be expected in any programming language. 18 Creating Folders The creation of a folder is done with the assistance of the MD (Make directory) command. 19 Listing Folder Contents The listing of folder contents can be done with the dir command. This command allows you to see the available files and directories in the current directory. 20 Deleting Folders For deleting folders, Batch Scripting provides the DEL command. 21 Renaming Folders For renaming folders, Batch Script provides the REN or RENAME command. 22 Moving Folders For moving folders, Batch Script provides the MOVE command. Print Page Previous Next Advertisements ”;
Batch Script – Arrays
Batch Script – Arrays ”; Previous Next Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script. Each element of the array needs to be defined with the set command. The ‘for’ loop would be required to iterate through the values of the array. Creating an Array An array is created by using the following set command. set a[0]=1 Where 0 is the index of the array and 1 is the value assigned to the first element of the array. Another way to implement arrays is to define a list of values and iterate through the list of values. The following example show how this can be implemented. Example @echo off set list=1 2 3 4 (for %%a in (%list%) do ( echo %%a )) Output The above command produces the following output. 1 2 3 4 Accessing Arrays You can retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array. Example @echo off set a[0]=1 echo %a[0]% In this example, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Let”s check the following example to create, initialize and access arrays − @echo off set a[0]=1 set a[1]=2 set a[2]=3 echo The first element of the array is %a[0]% echo The second element of the array is %a[1]% echo The third element of the array is %a[2]% The above command produces the following output. The first element of the array is 1 The second element of the array is 2 The third element of the array is 3 Modifying an Array To add an element to the end of the array, you can use the set element along with the last index of the array element. Example @echo off set a[0]=1 set a[1]=2 set a[2]=3 Rem Adding an element at the end of an array Set a[3]=4 echo The last element of the array is %a[3]% The above command produces the following output. The last element of the array is 4 You can modify an existing element of an Array by assigning a new value at a given index as shown in the following example − @echo off set a[0]=1 set a[1]=2 set a[2]=3 Rem Setting the new value for the second element of the array Set a[1]=5 echo The new value of the second element of the array is %a[1]% The above command produces the following output. The new value of the second element of the array is 5 Iterating Over an Array Iterating over an array is achieved by using the ‘for’ loop and going through each element of the array. The following example shows a simple way that an array can be implemented. @echo off setlocal enabledelayedexpansion set topic[0]=comments set topic[1]=variables set topic[2]=Arrays set topic[3]=Decision making set topic[4]=Time and date set topic[5]=Operators for /l %%n in (0,1,5) do ( echo !topic[%%n]! ) Following things need to be noted about the above program − Each element of the array needs to be specifically defined using the set command. The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array. Output The above command produces the following output. Comments variables Arrays Decision making Time and date Operators Length of an Array The length of an array is done by iterating over the list of values in the array since there is no direct function to determine the number of elements in an array. @echo off set Arr[0]=1 set Arr[1]=2 set Arr[2]=3 set Arr[3]=4 set “x = 0” :SymLoop if defined Arr[%x%] ( call echo %%Arr[%x%]%% set /a “x+=1” GOTO :SymLoop ) echo “The length of the array is” %x% Output Output The above command produces the following output. 1 2 3 4 “The length of the array is” 4 Creating Structures in Arrays Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved. Example @echo off set obj[0].Name=Joe set obj[0].ID=1 set obj[1].Name=Mark set obj[1].ID=2 set obj[2].Name=Mohan set obj[2].ID=3 FOR /L %%i IN (0 1 2) DO ( call echo Name = %%obj[%%i].Name%% call echo Value = %%obj[%%i].ID%% ) The following key things need to be noted about the above code. Each variable defined using the set command has 2 values associated with each index of the array. The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3. We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code. We are able to access each element of the structure using the obj[%i%] notation. Output The above command produces the following output. Name=Joe Value=1 Name=Mark Value=2 Name=Mohan Value=3 Print Page Previous Next Advertisements ”;
Batch Script – Decision Making ”; Previous Next Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. S.No Strings & Description 1 If Statement The first decision-making statement is the ‘if’ statement. 2 If/else Statement The next decision making statement is the If/else statement. Following is the general form of this statement. 3 Nested If Statements Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each other. Following is the general form of this statement. Print Page Previous Next Advertisements ”;
Batch Script – Syntax
Batch Script – Syntax ”; Previous Next Normally, the first line in a batch file often consists of the following command. ECHO Command @echo off By default, a batch file will display its command as it runs. The purpose of this first command is to turn off this display. The command “echo off” turns off the display for the whole script, except for the “echo off” command itself. The “at” sign “@” in front makes the command apply to itself as well. Documentation Very often batch files also contains lines that start with the “Rem” command. This is a way to enter comments and documentation. The computer ignores anything on a line following Rem. For batch files with increasing amount of complexity, this is often a good idea to have comments. First Batch Script Program Let’s construct our simple first batch script program. Open notepad and enter the following lines of code. Save the file as “List.cmd”. The code does the following − Uses the echo off command to ensure that the commands are not shown when the code is executed. The Rem command is used to add a comment to say what exactly this batch file does. The dir command is used to take the contents of the location C:Program Files. The ‘>’ command is used to redirect the output to the file C:lists.txt. Finally, the echo command is used to tell the user that the operation is completed. @echo off Rem This is for listing down all the files in the directory Program files dir “C:Program Files” > C:lists.txt echo “The program has completed” When the above command is executed, the names of the files in C:Program Files will be sent to the file C:Lists.txt and in the command prompt the message “The program has completed” will be displayed. Print Page Previous Next Advertisements ”;