Pac is not recognized as an internal or external command, operable program or batch file
Batch Script - OverviewBatch Script is incorporated to automate command sequences which are repetitive in nature. 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. In most organizations, Batch Script is incorporated in some way or the other to automate stuff. Show
Some of the features of Batch Script are −
Some of the common uses of Batch Script are −
Batch scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. On Windows systems, this interpreter is known as cmd.exe. Running a batch file is a simple matter of just clicking on it. Batch files can also be run in a command prompt or the Start-Run line. In such case, the full path name must be used unless the file's path is in the path environment. Following is a simple example of a Batch Script. This Batch Script when run deletes all files in the current directory. :: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR Batch Script - EnvironmentThis chapter explains the environment related to Batch Script. Writing and ExecutingTypically, to create a batch file, notepad is used. This is the simplest tool for creation of batch files. Next is the execution environment for the batch scripts. On Windows systems, this is done via the command prompt or cmd.exe. All batch files are run in this environment. Following are the different ways to launch cmd.exe − Method 1 − Go to C:\Windows\System32 and double click on the cmd file. Method 2 − Via the run command – The following snapshot shows to find the command prompt(cmd.exe) on Windows server 2012. Once the cmd.exe is launched, you will be presented with the following screen. This will be your environment for executing your batch scripts. Environment VariablesIn order to run batch files from the command prompt, you either need to go to the location to where the batch file is stored or alternatively you can enter the file location in the path environment variable. Thus assuming that the
batch file is stored in the location
Batch Script - CommandsIn this chapter, we will look at some of the frequently used batch commands.
Batch Script - FilesIn this chapter, we will learn how to create, save, execute, and modify batch files. Creating Batch FilesBatch files are normally created in notepad. Hence the simplest way is to open notepad and enter the commands required for the script. For this exercise, open notepad and enter the following statements. :: Deletes All files in the Current Directory With Prompts and Warnings ::(Hidden, System, and Read-Only Files are Not Affected) :: @ECHO OFF DEL . DR Saving Batch FilesAfter your batch file is created, the next step is to save your batch file. Batch files have the extension of either .bat or .cmd. Some general rules to keep in mind when naming batch files −
The above screenshot shows how to save the batch file. When saving your batch file a few points to keep in mind.
Executing Batch FilesFollowing are the steps to execute a batch file −
Modifying Batch FilesFollowing are the steps for modifying an existing batch file.
Batch Script - SyntaxNormally, 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. DocumentationVery 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 ProgramLet’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 −
@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. Batch Script - VariablesThere are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command. Command Line ArgumentsBatch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen. @echo off echo %1 echo %2 echo %3 If the above batch script is stored in a file called test.bat and we were to run the batch as Test.bat 1 2 3 Following is a screenshot of how this would look in the command prompt when the batch file is executed. The above command produces the following output. 1 2 3 If we were to run the batch as Example 1 2 3 4 The output would still remain the same as above. However, the fourth parameter would be ignored. Set CommandThe other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command. Syntaxset /A variable-name=value where,
The following example shows a simple way the set command can be used. Example@echo off set message=Hello World echo %message%
OutputThe above command produces the following output. Hello World Working with Numeric ValuesIn batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch. The following code shows a simple way in which numeric values can be set with the /A switch. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c%
The output of the above program would be 15. All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files. @echo off SET /A a = 5 SET /A b = 10 SET /A c = %a% + %b% echo %c% SET /A c = %a% - %b% echo %c% SET /A c = %b% / %a% echo %c% SET /A c = %b% * %a% echo %c% The above command produces the following output. 15 -5 2 50 Local vs Global VariablesIn any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed. DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script. Example@echo off set globalvar = 5 SETLOCAL set var = 13145 set /A var = %var% + 5 echo %var% echo %globalvar% ENDLOCAL Few key things to note about the above program.
OutputThe above command produces the following output. 13150 5 You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist. Working with Environment VariablesIf you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications. @echo off echo %JAVA_HOME% The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output. C:\Atlassian\Bitbucket\4.0.1\jre Batch Script - CommentsIt’s always a good practice to add comments or documentation for the scripts which are created. This is required for maintenance of the scripts to understand what the script actually does. For example, consider the following piece of code which has no form of comments. If any average person who has not developed the following script tries to understand the script, it would take a lot of time for that person to understand what the script actually does. ECHO OFF IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax SETLOCAL SET WSS= IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A ENDLOCAL GOTO:EOF ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed Comments Using the Rem StatementThere are two ways to create comments in Batch Script; one is via the Rem command. Any text which follows the Rem statement will be treated as comments and will not be executed. Following is the general syntax of this statement. SyntaxRem Remarks where ‘Remarks’ is the comments which needs to be added. The following example shows a simple way the Rem command can be used. Example@echo off Rem This program just displays Hello World set message=Hello World echo %message% OutputThe above command produces the following output. You will notice that the line with the Rem statement will not be executed. Hello World Comments Using the :: StatementThe other way to create comments in Batch Script is via the :: command. Any text which follows the :: statement will be treated as comments and will not be executed. Following is the general syntax of this statement. Syntax:: Remarks where ‘Remarks’ is the comment which needs to be added. The following example shows a simple way the Rem command can be used. Example@echo off :: This program just displays Hello World set message = Hello World echo %message% OutputThe above command produces the following output. You will notice that the line with the :: statement will not be executed. Hello World Note − If you have too many lines of Rem, it could slow down the code, because in the end each line of code in the batch file still needs to be executed. Let’s look at the example of the large script we saw at the beginning of this topic and see how it looks when documentation is added to it. ::=============================================================== :: The below example is used to find computer and logged on users :: ::=============================================================== ECHO OFF :: Windows version check IF NOT "%OS%"=="Windows_NT" GOTO Syntax ECHO.%* | FIND "?" >NUL :: Command line parameter check IF NOT ERRORLEVEL 1 GOTO Syntax IF NOT [%2]==[] GOTO Syntax :: Keep variable local SETLOCAL :: Initialize variable SET WSS= :: Parse command line parameter IF NOT [%1]==[] FOR /F "tokens = 1 delims = \ " %%A IN ('ECHO.%~1') DO SET WSS = %%A :: Use NET VIEW and NBTSTAT to find computers and logged on users FOR /F "tokens = 1 delims = \ " %%a IN ('NET VIEW ^| FIND /I "\\%WSS%"') DO FOR /F "tokens = 1 delims = " %%A IN ('NBTSTAT -a %%a ^| FIND /I /V "%%a" ^| FIND "<03>"') DO ECHO.%%a %%A :: Done ENDLOCAL GOTO:EOF :Syntax ECHO Display logged on users and their workstations. ECHO Usage: ACTUSR [ filter ] IF "%OS%"=="Windows_NT" ECHO Where: filter is the first part of the computer name^(s^) to be displayed You can now see that the code has become more understandable to users who have not developed the code and hence is more maintainable. Batch Script - StringsIn DOS, a string is an ordered collection of characters, such as "Hello, World!".
Batch Script - ArraysArrays 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.
Creating an ArrayAn 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 )) OutputThe above command produces the following output. 1 2 3 4 Accessing ArraysYou 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 ArrayTo 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 ArrayIterating 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 −
OutputThe above command produces the following output. Comments variables Arrays Decision making Time and date Operators Length of an ArrayThe 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% OutputOutput The above command produces the following output. The length of the array is 4 Creating Structures in ArraysStructures 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 len = 3 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 set i = 0 :loop if %i% equ %len% goto :eof set cur.Name= set cur.ID= for /f "usebackq delims==.tokens=1-3" %%j in (`set obj[%i%]`) do ( set cur.%%k=%%l ) echo Name = %cur.Name% echo Value = %cur.ID% set /a i = %i%+1 goto loop The following key things need to be noted about the above code.
OutputThe above command produces the following output. Name = Joe Value = 1 Name = Mark Value = 2 Name = Mohan Value = 3 Batch Script - Decision MakingDecision-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.
Batch Script - OperatorsAn operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. In batch script, the following types of operators are possible.
Arithmetic OperatorsBatch script language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available. Show Example
Relational OperatorsRelational operators allow of the comparison of objects. Below are the relational operators available. Show Example
Logical OperatorsLogical operators are used to evaluate Boolean expressions. Following are the logical operators available. The batch language is equipped with a full set of Boolean logic operators like AND, OR, XOR, but only for binary numbers. Neither are there any values for TRUE or FALSE. The only logical operator available for conditions is the NOT operator. Show Example
Assignment OperatorsBatch Script language also provides assignment operators. Following are the assignment operators available. Show Example
Bitwise OperatorsBitwise operators are also possible in batch script. Following are the operators available. Show Example
Following is the truth table showcasing these operators.
Batch Script - DATE and TIMEThe date and time in DOS Scripting have the following two basic commands for retrieving the date and time of the system. DATEThis command gets the system date. SyntaxDATE Example@echo off echo %DATE% OutputThe current date will be displayed in the command prompt. For example, Mon 12/28/2015 TIMEThis command sets or displays the time. SyntaxTIME Example@echo off echo %TIME% OutputThe current system time will be displayed. For example, 22:06:52.87 Following are some implementations which can be used to get the date and time in different formats. Date in Format Year-Month-DayExample@echo off echo/Today is: %year%-%month%-%day% goto :EOF setlocal ENABLEEXTENSIONS set t = 2&if "%date%z" LSS "A" set t = 1 for /f "skip=1 tokens = 2-4 delims = (-)" %%a in ('echo/^|date') do ( for /f "tokens = %t%-4 delims=.-/ " %%d in ('date/t') do ( set %%a=%%d&set %%b=%%e&set %%c=%%f)) endlocal&set %1=%yy%&set %2=%mm%&set %3=%dd%&goto :EOF OutputThe above command produces the following output. Today is: 2015-12-30 Batch Script - Input / OutputThere are three universal “files” for keyboard input, printing text on the screen and printing errors on the screen. 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. Finally, the “Standard Err” file, known as stderr, contains any error messages for display on the screen. Each of these three standard files, otherwise known as the standard streams, are referenced using the numbers 0, 1, and 2. Stdin is file 0, stdout is file 1, and stderr is file 2. Redirecting Output (Stdout and Stderr)One common practice in batch files is sending the output of a program to a log file. The > operator sends, or redirects, stdout or stderr to another file. The following example shows how this can be done. Dir C:\ > list.txt In the above example, the stdout of the command Dir C:\ is redirected to the file list.txt. If you append the number 2 to the redirection filter, then it would redirect the stderr to the file lists.txt. Dir C:\ 2> list.txt One can even combine the stdout and stderr streams using the file number and the ‘&’ prefix. Following is an example. DIR C:\ > lists.txt 2>&1 Suppressing Program OutputThe pseudo file NUL is used to discard any output from a program. The following example shows that the output of the command DIR is discarded by sending the output to NUL. Dir C:\ > NUL StdinTo work with the Stdin, you have to use a workaround to achieve this. This can be done by redirecting the command prompt’s own stdin, called CON. The following example shows how you can redirect the output to a file called lists.txt. After you execute the below command, the command prompt will take all the input entered by user till it gets an EOF character. Later, it sends all the input to the file lists.txt. TYPE CON > lists.txt Batch Script - Return CodeBy default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly. Following are the common exit code and their description.
Error LevelThe environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. By default, the way to check for the ERRORLEVEL is via the following code. SyntaxIF %ERRORLEVEL% NEQ 0 ( DO_Something ) It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file. EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes. Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers. Let’s look at a quick example on how to check for error codes from a batch file. ExampleLet’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9. if not exist c:\lists.txt exit 7 if not defined userprofile exit 9 exit 0 Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0. Call Find.cmd if errorlevel gtr 0 exit echo “Successful completion” OutputIn the above program, we can have the following scenarios as the output −
LoopsIn the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.
Looping through Command Line ArgumentsThe ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments. Example@ECHO OFF :Loop IF "%1"=="" GOTO completed FOR %%F IN (%1) DO echo %%F SHIFT GOTO Loop :completed OutputLet’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3. 1 2 3
Batch Script - FunctionsA 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 DefinitionIn 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
Following is an example of a simple function. Example:Display SET /A index=2 echo The value of index is %index% EXIT /B 0
Batch Script - ProcessIn this chapter, we will discuss the various processes involved in Batch Script. Viewing the List of Running ProcessesIn Batch Script, the TASKLIST command can be used to get the list of currently running processes within a system. SyntaxTASKLIST [/S system [/U username [/P [password]]]] [/M [module] | /SVC | /V] [/FI filter] [/FO format] [/NH]
ExamplesTASKLIST 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 ProcessAllows 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. SyntaxTASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]
Examplestaskkill /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 ProcessDOS scripting also has the availability to start a new process altogether. This is achieved by using the START command. SyntaxSTART "title" [/D path] [options] "command" [parameters] Wherein
ExamplesSTART "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 Files\Microsoft Office\Winword.exe" "D:\test\TESTA.txt" The above command will actually run Microsoft word in another process and then open the file TESTA.txt in MS Word. Batch Script - AliasesAliases means creating shortcuts or keywords for existing commands. Suppose if we wanted to execute the below command which is nothing but the directory listing command with the /w option to not show all of the necessary details in a directory listing. Dir /w Suppose if we were to create a shortcut to this command as follows. dw = dir /w When we want to execute the dir /w command, we can simply type in the word dw. The word ‘dw’ has now become an alias to the command Dir /w. Creating an AliasAlias are managed by using the doskey command. SyntaxDOSKEY [options] [macroname=[text]] Wherein
Following are the description of the options which can be presented to the DOSKEY command.
ExampleCreate a new file called keys.bat and enter the following commands in the file. The below commands creates two aliases, one if for the cd command, which automatically goes to the directory called test. And the other is for the dir command. @echo off doskey cd = cd/test doskey d = dir Once you execute the command, you will able to run these aliases in the command prompt. OutputThe following screenshot shows that after the above created batch file is executed, you can freely enter the ‘d’ command and it will give you the directory listing which means that your alias has been created. Deleting an AliasAn alias or macro can be deleted by setting the value of the macro to NULL. Example@echo off doskey cd = cd/test doskey d = dir d= In the above example, we are first setting the macro d to d = dir. After which we are setting it to NULL. Because we have set the value of d to NULL, the macro d will deleted. Replacing an AliasAn alias or macro can be replaced by setting the value of the macro to the new desired value. Example@echo off doskey cd = cd/test doskey d = dir d = dir /w In the above example, we are first setting the macro d to d = dir. After which we are setting it to dir /w. Since we have set the value of d to a new value, the alias ‘d’ will now take on the new value. Batch Script - DevicesWindows now has an improved library which can be used in Batch Script for working with devices attached to the system. This is known as the device console – DevCon.exe. Windows driver developers and testers can use DevCon to verify that a driver is installed and configured correctly, including the proper INF files, driver stack, driver files, and driver package. You can also use the DevCon commands (enable, disable, install, start, stop, and continue) in scripts to test the driver. DevCon is a command-line tool that performs device management functions on local computers and remote computers. Display driver and device info DevCon can display the following properties of drivers and devices on local computers, and remote computers (running Windows XP and earlier) −
DevCon (DevCon.exe) is included when you install the WDK, Visual Studio, and the Windows SDK for desktop apps. DevCon.exe kit is available in the following locations when installed. %WindowsSdkDir%\tools\x64\devcon.exe %WindowsSdkDir%\tools\x86\devcon.exe %WindowsSdkDir%\tools\arm\devcon.exe Syntaxdevcon [/m:\\computer] [/r] command [arguments] wherein
ExamplesFollowing are some examples on how the DevCon command is used. List all driver files The following command uses the DevCon DriverFiles operation to list the file names of drivers that devices on the system use. The command uses the wildcard character (*) to indicate all devices on the system. Because the output is extensive, the command uses the redirection character (>) to redirect the output to a reference file, driverfiles.txt. devcon driverfiles * > driverfiles.txt The following command uses the DevCon status operation to find the status of all devices on the local computer. It then saves the status in the status.txt file for logging or later review. The command uses the wildcard character (*) to represent all devices and the redirection character (>) to redirect the output to the status.txt file. devcon status * > status.txt The following command enables all printer devices on the computer by specifying the Printer setup class in a DevCon Enable command. The command includes the /r parameter, which reboots the system if it is necessary to make the enabling effective. devcon /r enable = Printer The following command uses the DevCon Install operation to install a keyboard device on the local computer. The command includes the full path to the INF file for the device (keyboard.inf) and a hardware ID (*PNP030b). devcon /r install c:\windows\inf\keyboard.inf *PNP030b The following command will scan the computer for new devices. devcon scan The following command will rescan the computer for new devices. devcon rescan Batch Script - RegistryThe 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.
Batch Script - NetworkBatch 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.
Batch Script - PrintingPrinting can also be controlled from within Batch Script via the NET PRINT command. SyntaxPRINT [/D:device] [[drive:][path]filename[...]] Where /D:device - Specifies a print device. Exampleprint c:\example.txt /c /d:lpt1 The above command will print the example.txt file to the parallel port lpt1. Command Line Printer ControlAs of Windows 2000, many, but not all, printer settings can be configured from Windows's command line using PRINTUI.DLL and RUNDLL32.EXE SyntaxRUNDLL32.EXE PRINTUI.DLL,PrintUIEntry [ options ] [ @commandfile ] Where some of the options available are the following −
Testing if a Printer ExistsThere can be cases wherein you might be connected to a network printer instead of a local printer. In such cases, it is always beneficial to check if a printer exists in the first place before printing. The existence of a printer can be evaluated with the help of the RUNDLL32.EXE PRINTUI.DLL which is used to control most of the printer settings. ExampleSET PrinterName = Test Printer SET file=%TEMP%\Prt.txt RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /Xg /n "%PrinterName%" /f "%file%" /q IF EXIST "%file%" ( ECHO %PrinterName% printer exists ) ELSE ( ECHO %PrinterName% printer does NOT exists ) The above command will do the following −
Batch Script - DebuggingDebugging 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 commandA 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 OutputC:\>test.bat 10 2 4 6 8 10 22 Press any key to continue ... Using pause commandAnother 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 OutputC:\>test.bat input value not provided Press any key to continue.. Logging the error messages to another fileIt 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 themErrorlevel 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 . . . Batch Script - LoggingLogging in is possible in Batch Script by using the redirection command. Syntaxtest.bat > testlog.txt 2> testerrors.txt ExampleCreate 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. OutputIf 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 How do I open the Power platform command line?Install using Power Platform Tools for Visual Studio Code. Open Visual Studio Code.. Select the Extensions icon from the Activity panel. ... . Select Install. ... . Optionally, you can initiate the install into Visual Studio Code directly from Marketplace and it will launch Visual Studio Code and commence the extension installation.. How do you package a PCF component?Deploying code components. Ensure that you have a valid authentication profile created.. Navigate to the directory where the sample component file is located.. Run the pac pcf push command. CLI Copy. pac pcf push --publisher-prefix What is power apps CLI?Use Microsoft Power Platform CLI (command-line interface) to create, debug, and deploy code components using Power Apps component framework. Microsoft Power Platform CLI enables developers to create code components quickly.
What is Powerapps component framework?Power Apps component framework empowers professional developers and app makers to create code components for model-driven and canvas apps. These code components can be used to enhance the user experience for users working with data on forms, views, dashboards, and canvas app screens.
|