Как вывести ошибку bat

I have a batch file that runs a couple executables, and I want it to exit on success, but stop if the exit code <> 0. How do I do this?

asked Aug 10, 2010 at 18:12

Dlongnecker's user avatar

Sounds like you’ll want the «If Errorlevel» command. Assuming your executable returns a non-0 exit code on failure, you do something like:

myProgram.exe
if errorlevel 1 goto somethingbad
echo Success!
exit
:somethingbad
echo Something Bad Happened.

Errorlevel checking is done as a greater-or-equal check, so any non-0 exit value will trigger the jump. Therefore, if you need to check for more than one specific exit value, you should check for the highest one first.

answered Aug 10, 2010 at 18:20

Hellion's user avatar

HellionHellion

1,74028 silver badges36 bronze badges

5

You can also use conditional processing symbols to do a simple success/failure check. For example:

myProgram.exe && echo Done!

would print Done! only if myProgram.exe returned with error level 0.

myProgram.exe || PAUSE

would cause the batch file to pause if myProgram.exe returns a non-zero error level.

answered Aug 11, 2010 at 5:55

Cheran Shunmugavel's user avatar

4

A solution better than Hellion’s answer is checking the %ERRORLEVEL% environment variable:

IF %ERRORLEVEL% NEQ 0 (
  REM do something here to address the error
)

It executes the IF body, if the return code is anything other than zero, not just values greater than zero.

The command IF ERRORLEVEL 1 ... misses the negative return values. Some progrmas may also use negative values to indicate error.

BTW, I love Cheran’s answer (using && and || operators), and recommend that to all.

For more information about the topic, read this article

answered Sep 24, 2019 at 11:47

Moha Dehghan's user avatar

Moha DehghanMoha Dehghan

17.9k3 gold badges55 silver badges72 bronze badges

Error Handling in Batch Script

Every scripting and programming language contains an error handler like Java contains try-catch for error handling. In a Batch script, there is no direct way to do this, but we can create an error handler in the Batch script using a built-in variable of the Batch script name %ERRORLEVEL%.

This article will show how we can create a Batch script to handle errors and failures. Also, we are going to some examples that make the topic easier.

Error Handling in Batch Script

When a command successfully executes, it always returns an EXIT CODE that indicates whether the command successfully executed or failed to execute. So, to create an error handling in a Batch file, we can use that EXIT CODE in our program.

You can follow below general format to create an error handler:

@Echo off
SomeCommand && (
  ECHO Message for Success
) || (
  ECHO Message for Failure or Error
)

We can also do that by checking the variable named %ERRORLEVEL%. If the variable contains a value not equal to 0, then there might be a problem or error when executing the command. To test the %ERRORLEVEL% variable, you can follow the below example codes:

@ECHO off
Some Command Here !!!
IF %ERRORLEVEL% NEQ 0 (Echo Error found when running the command &Exit /b 1)

You must note that the keyword NEQ means Not Equal. And the variable %ERRORLEVEL% will only contain a non-zero value if there is a problem or error in the code.

An Example That Contains Errors

Below, we shared an example. We will run a Batch file named Your_file.bat from a location.

We intentionally removed that file from the directory. So it’s an error command.

The code for our example will be:

@echo off
ECHO Running a Batch file
CD G:\BATCH\
CALL Your_file.bat
IF  errorlevel 1 GOTO ERROR
ECHO The file run successfully.
GOTO EOF

:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1

:EOF

Now, as the file doesn’t exist in the directory, it will show an error, and you will get the below output when you run the code shared above.

Output:

Running a Batch file
The system cannot find the path specified.
'Your_file.bat' is not recognized as an internal or external command,
operable program or batch file.
The file didn't run successfully.

An Error-Free Code Example That Runs Successfully

In the example above, we made a mistake on the code intentionally to understand how the code works. If we correct it like below:

@echo off
ECHO Running a Batch file
CALL "G:\BATCH\Yourfile.bat"
IF  errorlevel 1 GOTO ERROR
ECHO The file runs successfully.
GOTO EOF

:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1

:EOF

Then we will get an output like this:

Running a Batch file
This is from the first file
The file runs successfully.

Remember, all commands we discussed here are only for the Windows Command Prompt or CMD environment.

Topic: How to return success/failure from a batch file?  (Read 197798 times)

0 Members and 1 Guest are viewing this topic.

grevesz

Hello,

I am new to the DOS world. Could someone please help with these questions:

How do I return 0 for success ate the end of an MSDOS batch file?
Similarly, how do I return 1 (or other values) representing erroneous execution?

Thanks in advance!

Gabor


Logged


diablo416

heres an example

@echo off
setlocal enabledelayedexpansion
ping 127.0.0.1
if «%errorlevel%»==»0» cls &Echo Success.
if «%errorlevel%»==»1» cls &Echo Fail
endlocal


Logged


grevesz

Thanks, but that’s not exactly what I had in mind. Let me try to explain it in a different way:
a.bat calls b.bat and when b.bat completes, a.bat continues with steps depending on whether b.bat succeeded or failed.

a.bat:

rem some code here
call b.bat
if "%errorlevel%=="0" goto success
:failure
rem do something
goto end
:success
rem do something else
:end

What would b.bat look like for a.bat to work?

Thanks again!

Gabor


Logged


fireballs

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

What is wrong with the code you provided below?

FB


Logged

Next time google it.


Sidewinder

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

Not quite. Not all MS commands fail with errorlevel 1. XCOPY, for instance can fail with errorlevels 1 to 5. This type of compare («%errorlevel%==»0») becomes dubious at best.

B.bat can use the exit statement to pass a return code (errorlevel) back to a.bat.

Quits the CMD.EXE program (command interpreter) or the current batch
script.

EXIT [/B] [exitCode]

  /B          specifies to exit the current batch script instead of
              CMD.EXE.  If executed from outside a batch script, it
              will quit CMD.EXE

  exitCode    specifies a numeric number.  if /B is specified, sets
              ERRORLEVEL that number.  If quitting CMD.EXE, sets the process
              exit code with that number.

 

8)


Logged

The true sign of intelligence is not knowledge but imagination.

— Albert Einstein


fireballs

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

Not quite. Not all MS commands fail with errorlevel 1. XCOPY, for instance can fail with errorlevels 1 to 5. This type of compare («%errorlevel%==»0») becomes dubious at best.

B.bat can use the exit statement to pass a return code (errorlevel) back to a.bat.

Quits the CMD.EXE program (command interpreter) or the current batch
script.

EXIT [/B] [exitCode]

  /B          specifies to exit the current batch script instead of
              CMD.EXE.  If executed from outside a batch script, it
              will quit CMD.EXE

  exitCode    specifies a numeric number.  if /B is specified, sets
              ERRORLEVEL that number.  If quitting CMD.EXE, sets the process
              exit code with that number.

 8)

yes there are instances where the errorlevel won’t be 1 choice returns 254 if there’s an error. exit requires that you use the same if error gtr 0 but with exit as the command

FB


Logged

Next time google it.


Sidewinder

exit requires that you use the same if error gtr 0 but with exit as the command

Don’t really understand this. I was thinking more along the line where b.bat would abort early based on some condition:

b.bat

if not exist c:\file.ext exit 7
if not defined userprofile exit 9
exit 0

a.bat could the query the errorlevel and proceed accordingly, which is what I interpreted the OP requested.

 8)


Logged

The true sign of intelligence is not knowledge but imagination.

— Albert Einstein


fireballs

exit requires that you use the same if error gtr 0 but with exit as the command

Don’t really understand this. I was thinking more along the line where b.bat would abort early based on some condition:

b.bat

if not exist c:\file.ext exit 7
if not defined userprofile exit 9
exit 0

a.bat could the query the errorlevel and proceed accordingly, which is what I interpreted the OP requested.

 8)

sorry i’ve beed drinking so my post contained several spelling mistakes, what i meant is that you’d still have to specify under what conditions to exit with a specific exit condition using the if command.

it requires a finite amount of things that could be an error. if you use

if errorlevel gtr 0 exit /b [1] anything over errorleve==1 would exit with exit code 1

FB


Logged

Next time google it.


devcom

you can use:

&& if success
|| if fail

example:

set /a var=1/0 && echo A
set /a var=1/0 || echo A


Logged


grevesz

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

Not quite. Not all MS commands fail with errorlevel 1. XCOPY, for instance can fail with errorlevels 1 to 5. This type of compare («%errorlevel%==»0») becomes dubious at best.

B.bat can use the exit statement to pass a return code (errorlevel) back to a.bat.

Quits the CMD.EXE program (command interpreter) or the current batch
script.

EXIT [/B] [exitCode]

  /B          specifies to exit the current batch script instead of
              CMD.EXE.  If executed from outside a batch script, it
              will quit CMD.EXE

  exitCode    specifies a numeric number.  if /B is specified, sets
              ERRORLEVEL that number.  If quitting CMD.EXE, sets the process
              exit code with that number.

 8)

That’s exactly what I was looking for!
Thanks a lot!
Works like a charm!

Gabor


Logged


billrich

C:\>A.bat
 «Hello World»
 «Call  B.bat»
«We are in B.bat.»
«Return exit code from B.bat»
«errorlevel=77»
 77
Press any key to continue . . .
C:\>type A.bat
@ECHO OFF

echo  «Hello World»

echo  «Call  B.bat»

Call B.bat

echo «Return exit code from B.bat»

echo «errorlevel=%errorlevel%»
echo  %errorlevel%
pause

C:\>type B.bat
REM  return exit code to Batch A.bat
@ECHO OFF

echo «We are in B.bat.»

exit /B  77

C:\>


Logged


BC_Programmer

 

::)

a little late to the party, methinks…

Reply #9 on: September 10, 2008, 09:45:23 AM


Logged

I was trying to dereference Null Pointers before it was cool.


alfps

How do I return 0 for success ate the end of an MSDOS batch file?
Similarly, how do I return 1 (or other values) representing erroneous execution?

The most direct way is via

exit /b

value,

However, in Windows 8.1 at least, that doesn’t support

&&

and

||

in the invoking command.

To make those operators work, exit via the end of the batch file, where you place a

cmd /c exit

value, e.g.,

@echo off
setlocal
set E_FAIL=2147500037
set exit_code=%E_FAIL%

set /p a=Pretend to succeed (y/n)?
if "%a%"=="y" goto succeed

:fail
set exit_code=%E_FAIL% & goto finish

:succeed
set exit_code=0 & goto finish

:finish
cmd /c exit %exit_code%


For example, if that file is called

cmd_status.bat

, then you can test it with

cmd_status && echo OK || echo Bah


Logged


patio

The Topic is 6 Years old…
Don’t think he’ll return.


Logged

» Anyone who goes to a psychiatrist should have his head examined. «


alabamasuch

heres an example

@echo off
setlocal enabledelayedexpansion
ping 127.0.0.1
if «%errorlevel%»==»0» cls &Echo Success.
if «%errorlevel%»==»1» cls &Echo Fail
endlocal


Logged


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:

Last Updated :
28 Feb, 2022

Like Article

Save Article

I have a batch file that runs a couple executables, and I want it to exit on success, but stop if the exit code <> 0. How do I do this?

asked Aug 10, 2010 at 18:12

Dlongnecker's user avatar

Sounds like you’ll want the «If Errorlevel» command. Assuming your executable returns a non-0 exit code on failure, you do something like:

myProgram.exe
if errorlevel 1 goto somethingbad
echo Success!
exit
:somethingbad
echo Something Bad Happened.

Errorlevel checking is done as a greater-or-equal check, so any non-0 exit value will trigger the jump. Therefore, if you need to check for more than one specific exit value, you should check for the highest one first.

answered Aug 10, 2010 at 18:20

Hellion's user avatar

HellionHellion

1,74028 silver badges36 bronze badges

5

You can also use conditional processing symbols to do a simple success/failure check. For example:

myProgram.exe && echo Done!

would print Done! only if myProgram.exe returned with error level 0.

myProgram.exe || PAUSE

would cause the batch file to pause if myProgram.exe returns a non-zero error level.

answered Aug 11, 2010 at 5:55

Cheran Shunmugavel's user avatar

4

A solution better than Hellion’s answer is checking the %ERRORLEVEL% environment variable:

IF %ERRORLEVEL% NEQ 0 (
  REM do something here to address the error
)

It executes the IF body, if the return code is anything other than zero, not just values greater than zero.

The command IF ERRORLEVEL 1 ... misses the negative return values. Some progrmas may also use negative values to indicate error.

BTW, I love Cheran’s answer (using && and || operators), and recommend that to all.

For more information about the topic, read this article

answered Sep 24, 2019 at 11:47

Mohammad Dehghan's user avatar

Mohammad DehghanMohammad Dehghan

17.7k3 gold badges55 silver badges71 bronze badges

Error Handling in Batch Script

Every scripting and programming language contains an error handler like Java contains try-catch for error handling. In a Batch script, there is no direct way to do this, but we can create an error handler in the Batch script using a built-in variable of the Batch script name %ERRORLEVEL%.

This article will show how we can create a Batch script to handle errors and failures. Also, we are going to some examples that make the topic easier.

Error Handling in Batch Script

When a command successfully executes, it always returns an EXIT CODE that indicates whether the command successfully executed or failed to execute. So, to create an error handling in a Batch file, we can use that EXIT CODE in our program.

You can follow below general format to create an error handler:

@Echo off
SomeCommand && (
  ECHO Message for Success
) || (
  ECHO Message for Failure or Error
)

We can also do that by checking the variable named %ERRORLEVEL%. If the variable contains a value not equal to 0, then there might be a problem or error when executing the command. To test the %ERRORLEVEL% variable, you can follow the below example codes:

@ECHO off
Some Command Here !!!
IF %ERRORLEVEL% NEQ 0 (Echo Error found when running the command &Exit /b 1)

You must note that the keyword NEQ means Not Equal. And the variable %ERRORLEVEL% will only contain a non-zero value if there is a problem or error in the code.

An Example That Contains Errors

Below, we shared an example. We will run a Batch file named Your_file.bat from a location.

We intentionally removed that file from the directory. So it’s an error command.

The code for our example will be:

@echo off
ECHO Running a Batch file
CD G:BATCH
CALL Your_file.bat
IF  errorlevel 1 GOTO ERROR
ECHO The file run successfully.
GOTO EOF

:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1

:EOF

Now, as the file doesn’t exist in the directory, it will show an error, and you will get the below output when you run the code shared above.

Output:

Running a Batch file
The system cannot find the path specified.
'Your_file.bat' is not recognized as an internal or external command,
operable program or batch file.
The file didn't run successfully.

An Error-Free Code Example That Runs Successfully

In the example above, we made a mistake on the code intentionally to understand how the code works. If we correct it like below:

@echo off
ECHO Running a Batch file
CALL "G:BATCHYourfile.bat"
IF  errorlevel 1 GOTO ERROR
ECHO The file runs successfully.
GOTO EOF

:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1

:EOF

Then we will get an output like this:

Running a Batch file
This is from the first file
The file runs successfully.

Remember, all commands we discussed here are only for the Windows Command Prompt or CMD environment.


By 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 Code Description
0 Program successfully completed.
1 Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
2 The system cannot find the file specified. Indicates that the file cannot be found in specified location.
3 The system cannot find the path specified. Indicates that the specified path cannot be found.
5 Access is denied. Indicates that user has no access right to specified resource.

9009

0x2331

Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.

221225495

0xC0000017

-1073741801

Not enough virtual memory is available.

It indicates that Windows has run out of memory.

3221225786

0xC000013A

-1073741510

The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window.

3221225794

0xC0000142

-1073741502

The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize.

Error Level

The 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.

Syntax

IF %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.

Example

Let’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”

Output

In the above program, we can have the following scenarios as the output −

  • If the file c:lists.txt does not exist, then nothing will be displayed in the console output.

  • If the variable userprofile does not exist, then nothing will be displayed in the console output.

  • If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.

Loops

In 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.

S.No Loops & Description
1 While Statement Implementation

There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels.

2 For Statement — List Implementations

The «FOR» construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values.

3 Looping through Ranges

The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement.

4 Classic for Loop Implementation

Following is the classic ‘for’ statement which is available in most programming languages.

Looping through Command Line Arguments

The ‘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

Output

Let’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
S.No Loops & Description
1 Break Statement Implementation

The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

Эта статья рассказывает, какие возможности имеются в командном файле для привлечения внимания пользователя в случае какого-либо события или ошибки. Команды ECHO во многих случаях недостаточно, ведь это просто вывод текста, а хотелось бы, чтобы:

  • уведомление было заметным пользователю, даже если он в это время работает в другой программе
  • был удобный выбор для пользователя, какое действие bat файл должен сделать дальше
  • информация была наглядной, например, чтобы была видна серьёзность события (ошибка или просто информация)

В современных решения пользовательского интерфейса Windows уведомление работает не так, что окно внезапно выскакивает поверх всех, прерывая работу пользователя, теперь происходит вежливое мигание значком программы или командного файла на панели задач. Поэтому пользователь может спокойно продолжить свою работу, например, закончить какой-то документ, а затем щелкнуть по значку и посмотреть, что же там случилось.

Поднять окно командного файла

Чтобы поднять наверх окно командного файла, можно использовать возможности WSH: скрипт activate.js использует метод WshShell.AppActivate для окна, заголовок которого передаётся параметром командной строки:

var title = WScript.Arguments.Unnamed(0);
var wshshell = WScript.CreateObject("WScript.Shell");
wshshell.AppActivate(title);

Затем в командном файле устанавливаем заголовок окна и в нужный момент вызываем activate.js:

@echo off
set window_title=Мой bat файл
title %window_title%
rem Здесь выполняются команды...
if errorlevel 1 cscript //nologo activate.js "%window_title%" & pause

То есть если командный файл выполнился успешно, он тихо закрывается, не отвлекая пользователя. Если возникла ситуация, о которой нужно проинформировать пользователя, то окно поднимается наверх, показывая информацию об ошибке.

Этот скрипт можно переписать на VBScript.

Для наглядности будет полезно выделить цветом информацию о событии, например, об ошибке – красным цветом, о предупреждении – жёлтым и т.д..

Кроме этого, потребуется запрограммировать в bat файле выбор действия пользователем: с помощью pause для просто подтверждения, timeout для подтверждения с таймаутом или set /p для ввода значения.

В современных версиях Windows окно при выполнении этой команды окно не поднимается наверх, вместо этого начинает мигать значок на панели задач.

Показать всплывающее сообщение

Всплывающее сообщение MessageBox содержит текст со значком, это выглядит нагляднее, чем просто текст в консольном окне. Ещё в окне MessageBox могут быть различные сочетания кнопок (Да-Нет, ОК-Отмена и другие сочетания), с помощью которых пользователь может сделать свой выбор о выполняемых действиях.

Этот вариант использует возможности WSH и не требует установки  дополнительных программ.
Используется метод WshShell.Popup в скрипте popup.js

var text = WScript.Arguments.Unnamed(0);
var title = WScript.Arguments.Unnamed(1);
var wshshell = WScript.CreateObject("WScript.Shell");
wshshell.Popup(text,0,title,16);

Соответственно, командный файл вызывает его в случае ошибки:

cscript //nologo popup.js "Сбой процедуры полного резервного копирования. Сервер недоступен." "Резервное копирование"

Всплывающее окно NHMB

Программа nhmb также показывает всплывающее окно с выбором значка и кнопок, с возможностью задавать символы перевода строки, а также с отображением таймера в заголовке окна.

nhmb.exe "Сбой процедуры полного резервного копирования.nСервер недоступен." "Резервное копирование" error 60

В заголовке окна отображается время в секундах (55), оставшееся до автоматического закрытия окна и продолжения работы командного файла.

Все параметры всплывающего окна задаются в командной строке, и для удобства на странице программы есть генератор строки запуска, который формирует всю строку по требуемым условиям – нет необходимости разбираться в справке и тестировать команды, достаточно выбрать желаемое отображение и скопировать готовую строку в свой bat файл.

Онлайн генератор строки запуска программы nhmb на странице программы

Сравнение

Скрипт AppActivate Скрипт Popup Программа nhmb
Значок нет да да
Заголовок нет да да
Сообщение в несколько строк да да да
Команды с простым выбором нет да да
Команда по умолчанию с таймером нет есть, но таймер не отображается есть, таймер отображается
Требуется программирование да да нет

Узнать больше

Файлы для скачивания

Наши соцсети

Как сделать обработку исключений в CMD?
В python например так:

try:
  ... 
  print("Ошибок нет! ") 
except:
  print("Ошибка!")

  • Вопрос задан

    более года назад

  • 508 просмотров

КОМАНДА1 && КОМАНДА2
— вторая команда выполняется, если первая завершилась без ошибок.
КОМАНДА1 || КОМАНДА2
— вторая команда выполняется, если первая завершилась с ошибкой.

КОМАНДА && echo Ошибок нет! || echo Ошибка!

(Для объединения нескольких команд в составную можно использовать скобки, переносы строк или знак & между командами в одной строке. Для размещения одной простой команды на нескольких строках можно использовать ^ в конце переносимой строки…)

Пригласить эксперта


  • Показать ещё
    Загружается…

12 июн. 2023, в 17:27

1500 руб./за проект

12 июн. 2023, в 17:25

130000 руб./за проект

12 июн. 2023, в 16:48

700 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:
  • Как вы понимаете значение слова признать свои ошибки
  • Как вывести ошибку ajax
  • Как вывести ошибки php на экран
  • Как вы понимаете значение признавать свои ошибки
  • Как вывести коды ошибок на опель астра j