Windows bat file debug

Last Updated :
28 Feb, 2022

Batch Script is a text file that includes a definite amount of operations or commands that are performed in order. It is used in system networks as well as in system administration. It also eliminates a specific repetitive piece of work in various Operating Systems like DOS(Disk Operating System).

DebuggingIt is a process of removing errors from a program or computer in order to perform better.

Users can Identify the error in the batch script in the following ways:-

  • By adding pause command.
  • By working with the echo command.
  • Employ/Logging the error message to another file.
  • By using an environment variable (%ERRORLEVEL%) to detect errors.

By adding pause command: One way to debug batch file is by executing the pause command or operation and halting the executing program if any kind of error is found or occurred then a developer can easily fix the issue by restarting the process. In the below instance, batch script is paused as input value is compulsory to provide.

@echo off  
if [%2] == [] (  
  echo input value not provided  
  goto stop  
) else (  
  echo "Correct value"      
)  
:stop  
pause 

Working with the echo command: It’s quite an easy and basic option to debug the batch file. It will pop up a message wherever the error occurred.  In the below example the echo command is used to print the numbers as well as also in the place where the chance of error is higher.

@echo off  
if [%1] == [] (  
  echo input value not provided  
  goto stop  
)  
rem Print num  
for /l %%n in (2,2,%1) do (  
  echo "Numbers: " ,%%n  
)  
:stop  
pause 

Employ/Logging the error message to another file: It is hard to solve the issue just by looking at it in the command prompt window using the echo command. So we need to employ the errors into a separate file so that developers can easily look at the errors and can solve them.

Following is the eg of sample file:

net statistics /Server

Execute this command in your command line prompt on your PC:

C:\>sample.bat > samplelog.txt 2> sampleerrors.txt

The file sampleerrors .txt will display errors as given below:

By using an environment variable (%ERRORLEVEL%) to detect errors: The environmental variable %ERRORLEVEL% contains the return code or the latest error level in the batch file. This variable returns 1 in case of an incorrect function, 0 if it executes successfully, 2 shows that it can’t find a specified file in a particular location, 3 represents that system can’t able to find mentioned path, and 5 shows that access got denied. Error codes are also known as exit codes. At the end of the file EXIT command also returns the errors from a batch file. 

Syntax of above is given below:

IF %ERRORLEVEL% NEQ 0 Echo "Error was found"
IF %ERRORLEVEL% EQU 0 Echo "No error found"

You can also see the log file along with errors: samplelog.txt:

Rob van der Woude's Scripting Pages

Batch files will seldom be perfect right away.
This page describes some debugging techniques that will help you find and correct the issues.

Error messages

Often running a batch file will result in a cryptic error message between (or sometimes instead of) the expected output.
To discover the source of the message, follow these steps:

  1. REM out the @ECHO OFF line, i.e. REM @ECHO OFF or :: @ECHO OFF
  2. Run the batch file with the required command line parameters, redirecting all output to a log file for later comparison.
    For MS-DOS:

    mybatch.bat any_optional_parameters > mybatch.log

    For Windows NT 4 and later:

    mybatch.bat any_optional_parameters > mybatch.log 2>&1

    Search the file mybatch.log for the error message.
    Or, for Windows 2000 and later (download LOGBATCH.BAT first):

    LOGBATCH.BAT mybatch.bat any_optional_parameters

    Search the file mybatch_Test.log for the error message.

  3. Check the previous line for any unexpected or invalid command, command line switch(es) or value(s); pay special attention to the values of any environment variables used in the command.
  4. Correct the error and repeat this process until all error messages have disappeared.

Environment variables

A common source of errors are empty environment variables, or other unexpected values.
To check these values, follow these steps:

  1. Insert «variable check lines» just before a line which uses the value in a command to check the value of a variable.
    For MS-DOS:

    ECHO.MyVariable=%MyVariable%

    For Windows NT 4 and later:

    SET MyVariable

    This will return a line like:

    MyVariable=MyValue

  2. Follow the procedure to find error message sources described above.
Note: Make sure delayed variable expansion is enabled if variables are set inside FOR loops or code blocks (a code block consists of multiple commands, either placed between parentheses or «joined» into a single line with ampersands)

Complex command lines

Another common source of errors are incorrectly redirected commands, like for example «nested» FIND or FINDSTR commands with incorrect search strings, sometimes within a FOR /F loop.
Here’s a real-life example of such a one-liner:

FOR /F "tokens=8 delims=\" %%A IN ('TYPE %Temp%.\apipaorg.reg ^| FIND "[HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\TCPIP\Parameters\Interfaces\"') DO CALL :Enum "%%A"

To check the validity of these complex commands, follow these steps:

  1. Insert «command check lines» just before a line which uses the complex command set.
    Going back to our example, this is what you might insert:

    TYPE %Temp%.\apipaorg.reg
    ECHO.=====================================================
    TYPE %Temp%.\apipaorg.reg | FIND "[HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\TCPIP\Parameters\Interfaces\"

    Note: The ECHO command is inserted to mark where the output of the first TYPE command ends and the next one starts
  2. Follow the procedure to find error message sources described above.
    Pay special attention to the output of the «simplified» command lines: Is the output of the expected format? Is the «token» value or position as expected?

Subroutines

(Windows NT 4 and later)

Subroutines generating error messages pose an extra «challenge» in finding the cause of the error, as they may be called multiple times in the same batch file.
To help find out what causes the incorrect call to the subroutine, follow these steps:

  1. Add and reset a counter variable at the beginning of the script:

    SET Counter=0

  2. Increment the counter each time the subroutine is called, by inserting the following line at the beginning of the subroutine:

    SET /A Counter += 1

  3. Insert another line right after the counter increment, containing only the SET command; this will list all environment variables and their values.
  4. Follow the procedure to find error message sources described above.

Windows Versions

If you intend to distribute your batch files to other computers that may or may not run the same Windows version, you will need to test your batch files in as many Windows versions as possible.

Some, but not all, known compatibility issues are:

  • REG.EXE version 3.0 vs. 2.0 and older
  • Delayed variable expansion is not available in Windows NT 4 and possibly Windows 2000 base and earliest ServicePack
  • As of Windows XP, SET /A and IF can handle much larger integers
  • Windows XP’s ServicePack 2 introduced almost as many changes as a complete new Windows version would
  • NETSH options vary with Windows versions

The solution for compatibility issues with REG queries only is to issue the command twice, once for each version.
This technique is demonstrated in my iDate sample.

For testing of internal commands, I keep copies of CMD.EXE of all my previous Windows versions.
For ease of use I renamed them cmdNT4.exe, cmdW2K.exe, cmdXP.exe, cmdXP2.exe etcetera.
Now if I want to know if an internal command will work in NT 4 I use a command like this:

cmdNT4.exe /K DIR /?
Note: Use this trick carefully, the results won’t always be identical to the results when run in the full OS.
To demonstrate this, run cmdXXX.exe /K VER and compare the version and build numbers to those of the «host» OS’ own VER command.
Looks familiar?

But before distribution of your scripts you still need to run a full test on every Windows version the script is intended for.

If in doubt, you can control in which version(s) the batch file is allowed to run:

@ECHO OFF
:: Check for Windows NT 4 and later
IF NOT "%OS%"=="Windows_NT" GOTO DontRun
:: Check for Windows NT 4
VER | FIND "Windows NT" >NUL && GOTO DontRun
:: Check for Windows 2000
VER | FIND "Windows 2000" >NUL && GOTO DontRun

:: Place actual code here . . .
   •
   •
   •
:: End of actual code . . .
EXIT

:DontRun
ECHO Sorry, this batch file was written for Windows XP and later versions only
  • Dos and Donts When Writing Batch Files

page last modified: 2025-04-14; loaded in 0.0012 seconds

Yes, you can debug a .bat (batch) script in Windows by using the pause command and running the script from the command prompt. This will allow you to see the output of each command before it continues to the next one, and you can stop the execution at any time by pressing a key.

Here are the steps to debug your batch script:

  1. Open the command prompt (press Win + R and type cmd then hit Enter)
  2. Navigate to the directory where your batch script is located using the cd command. For example:
cd C:\path\to\your\script
  1. Type the name of your batch script and add pause at the end of it. For example:
myscript.bat pause
  1. Press Enter to run the script. The script will now run, and it will pause after each command, showing the output of that command.
  2. To stop the script execution, press any key.

Additionally, you can also redirect the output of your script to a text file for further analysis. To do that, add > output.txt at the end of your command, like this:

myscript.bat > output.txt

This will create a file called output.txt in the same directory where the script is located, and it will contain the output of the script.

If you want to check the order in which the other scripts are called, you can add an echo command before each call, like this:

echo Now calling script2.bat
call script2.bat
echo Now calling script3.bat
call script3.bat

This way, you will see a message on the screen every time a script is called, making it easier to track the order of execution.

  1. Can you debug a batch file?
  2. How do I check batch file errors?
  3. What is the meaning of %1 in batch?
  4. How do I pause a batch file?
  5. How do I debug a program running in the background?
  6. What is the use of Sy batch?
  7. What is batch job in as400?
  8. How can I get error in CMD?
  9. Does the syntax of the command is incorrect?
  10. What is a .bat file?
  11. What is call CMD?
  12. Can we debug shell script?
  13. How do I debug a file in Bash?

Can you debug a batch file?

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.

How do I check batch file errors?

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.

What is the meaning of %1 in batch?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.

How do I pause a batch file?

You can insert the pause command before a section of the batch file that you might not want to process. When pause suspends processing of the batch program, you can press CTRL+C and then press Y to stop the batch program.

How do I debug a program running in the background?

Go to transaction “SM50” find your running program in a process. Select the process -> click Program/Session -> Program -> Debugging. In debug mode, just change the value of lv_counter to something else and now, you are able to debug your dynamically called program in background.

What is the use of Sy batch?

SY-BATCH is the variable to check if your program is running in the background or not. If it carries the value ‘X’, this means that the program is running in the background. SY-BINPT is the variable to check if your program is being processed in a batch input session or not.

What is batch job in as400?

The Batch Job (BCHJOB) command indicates the beginning of a batch job in a batch input stream. It can also specify different values for the attributes for the job instead of the ones specified in the job description or user profile for this job.

How can I get error in CMD?

To test for a specific ERRORLEVEL, use an IF command with the %ERRORLEVEL% variable. n.b. Some errors may return a negative number. If the batch file is being executed as a scheduled task, then exiting with an error code will be logged as a failed task.

Does the syntax of the command is incorrect?

In the Windows command line, when trying to copy, move, or rename a file or directory with a space, you may get the «The syntax of the command is incorrect» error message. This error message is generated when the Windows command line does not understand the syntax of the command because it is not formatted properly.

What is a .bat file?

A batch file is a script file that stores commands to be executed in a serial order. It helps automate routine tasks without requiring user input or intervention. Some common applications of batch files include loading programs, running multiple processes or performing repetitive actions in a sequence in the system.

What is call CMD?

The call command enables a user to execute a batch file from within another batch file.

Can we debug shell script?

In the shell scripting we don”t have any debugger tool but with the help of command line options (-n, -v and -x ) we can do the debugging.

How do I debug a file in Bash?

The debugging options available in the Bash shell can be switched on and off in multiple ways. Within scripts, we can either use the set command or add an option to the shebang line. However, another approach is to explicitly specify the debugging options in the command-line while executing the script.

It’s important to remember the place that batch files
occupy in the hierarchy of automation. A batch represents a fast and
simple way of executing a series of tasks using applications, commands,
and utilities. The batch file possesses basic programming structures and
you can perform amazing tasks at times with those structures, but in
the end, batch files are somewhat limited. Something as simple as a disk
being full or a lack of rights to create a file in a specific location
can cause the batch file to fail. Error trapping in such cases is
difficult because you have to check for error levels from the errant
application, command, or utility and not every one of them supports
output error levels.

Real Administrators Use Batch Fiyles

At one time, I thought I
held the title for the number of batch files used for daily activities.
That’s until I ran into one network administrator who had more batch
files than I’d ever seen before. He had batch files for every occasion.
In fact, one of the batch files was simply there to track all of the
other batch files (so he didn’t reinvent the wheel at some point).

Of course, he didn’t
build this huge source of batch files in a day. In fact, he had been
building and refining them over a period of years. This administrator
customized many of the batch files to his way of working with systems
and the network as a whole. In fact, that’s the point of batch files.
You can do things your way. Because batch files are simplicity itself,
you can add, remove, and rebuild them as needed.

However, batch files
are important for administrators for another reason. Yet, the
time required to develop a batch file is short and you don’t need to
become a programmer to use one. These are the two reasons that most
administrators I’ve talked with give for using batch files instead of
scripts. Although batch files can’t replace scripts or full-fledged
programming languages, over the years I’ve found that batch files serve
the purpose for most administrator needs.


1. Adding Debug Information to Batch Files


Developers of most
applications know how to add debugging statements to their code. The
debugging statements aren’t for general use; they simply make it easier
to check the application for flaws. In addition, the debugging
statements make it possible to track program flow and generally help the
developer understand the application better. A batch file can also
include debugging information, even though there aren’t specific
statements to perform the task. The following code shows one method you
can use.


@IF NOT DEFINED DEBUG @ECHO OFF
ECHO
@ECHO ON

In this case, the debug trigger is an environment variable named DEBUG. You can set this environment variable to any value desired by using the Set command. Type Set DEBUG=
and press Enter to turn off debugging. The purpose of this debugging
statement is to keep echo on when you’re debugging the batch file.
During the debugging cycle, you want to see all of the statements, so
you display them by keeping the echo on. When the batch file runs
normally, the user won’t have an environment variable named DEBUG, and the batch file turns off echo so the user doesn’t see all of the intervening commands. Using the ECHO command by itself displays the current echo state so you can easily test this technique for yourself.


Notice that the batch file doesn’t include anything special for the @ECHO ON
statement. It’s bad practice to use conditional statements with
commands that set the system back to a default state. In this case, you
can set echo on without considering the current echo state because
having echo on is the default setting.


You can extend debugging
to other activities. For example, you might want to know the current
value of a variable within the batch file. Because you don’t have a
debugging environment that you can rely on to perform such tasks, you’ll
need to use other methods with a batch file. Listing 1
shows one technique you can use to extend a batch file to output
debugging information about an internal variable (note that this example
also uses the DEBUG environment variable).


Example 1. Adding Simple Debugging to a Batch File
@ECHO OFF

REM Locate all of the temporary files on your hard drive.
@ECHO Locating temporary files to delete.
FOR /F %%F IN (DelFiles.TXT) DO CALL :GetFile %%F
GOTO :NextStep

REM This is the actual code for handling the temporary file
REM processing.
:GetFile
IF DEFINED DEBUG @ECHO Adding %1 to the list.
Dir %1 /B /S >> DeleteMe.TXT
GOTO :EOF

REM You would normally place the next step of the processing
REM task here.
:NextStep

@ECHO ON



This is actually a batch
file within a batch file. The code begins by displaying information to
the user that it’s collecting a list of temporary files. At this point,
the user normally waits while the batch file does its job in complete
silence. However, as a developer, you really need to know what’s going
on within the batch file. To make this work, you need to execute
multiple commands. Consequently, the batch file calls a label named :GetFile and passes it to the %%F argument.


Now, look at the :GetFile label and you’ll see two statements. The first displays the current %%F value when you create an environment variable named DEBUG. However, notice that it’s called %1 here, not %%F. Whenever you employ a Call command to pass control to a label within a batch file, you create a new batch file context. As far as the :GetFile label is concerned, it exists in a different batch file from the original that called it. The first batch file passes %%F as an input value, so it appears as %1 to the :GetFile label code. The second statement in :GetFile is the Dir command that locates the files you want to delete based on the file specification.


Notice that the :GetFile section ends with GOTO :EOF, which should end the batch file. It does, in fact, end the :GetFile batch file and returns control to the FOR command that called it. Now the FOR command can process the next file extension in the list. Figure 1 gives you a better idea of how this batch file works with and without DEBUG defined. Notice the batch file doesn’t display the file extensions the first time because DEBUG isn’t defined yet.


The examples in this
section have only shown a single level of debugging so far. However, you
can create as many levels of debugging as you want by adding some
additional code. Listing 2shows the example in Listing 1 with a second level of debugging added. 


Example 2. A Batch File with Multiple Debug Levels Defined
IF NOT DEFINED DEBUG2 @ECHO OFF

REM Set the second level of debugging.
IF DEFINED DEBUG2 SET DEBUG=TRUE

REM Locate all of the temporary files on your hard drive.
@ECHO Locating temporary files to delete.
FOR /F %%F IN (DelFiles.TXT) DO CALL :GetFile %%F
GOTO :NextStep

REM This is the actual code for handling the temporary file
REM processing.
:GetFile
IF DEFINED DEBUG @ECHO Adding %1 to the list.
Dir %1 /B /S >> DeleteMe.TXT
Goto :EOF

REM You would normally place the next step of the processing
REM task here.
:NextStep

REM Always remember to remove additional debugging levels.
IF DEFINED DEBUG2 SET DEBUG=

@ECHO ON



The two levels of
debugging for this example are DEBUG and DEBUG2. When you define the
DEBUG2 level, the batch file automatically defines DEBUG for you and
then removes the DEBUG definition when the batch file ends. As shown in
the code, the DEBUG2 level displays all of the batch code as it
executes. Although this display can be handy, as shown in Figure 2,
it can also become quite messy. You don’t always need it to locate a
problem in your batch file. In fact, displaying the code can sometimes
hide problems in plain sight.


Figure 1. Batch files can output as little or much debugging information as needed.




Figure 2. Display code statements in batch files with care to avoid overwhelming yourself with too much content.




Many people claim that
batch files don’t offer any form of debugging. Admittedly, batch files
don’t provide the robust debugging features that full-fledged
programming languages do, but batch files don’t require these advanced
levels of debugging either since they normally perform simple tasks.
Using the techniques found in this section, you can provide at least a
modicum of debugging functionality for your batch files.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Установка windows на данный диск невозможно выбранный диск имеет стиль разделов гпт
  • Доменное имя пользователя windows
  • Kmsauto net источник https kms activator net kody aktivatsii dlya windows 7 x64 sborka 7601
  • Как уменьшить кнопку поиска в windows 10
  • Как улучшить звук в наушниках на компьютере windows 10 для игр