Bat обработка ошибок

I'm currently writing my first batch file for deploying an asp.net solution. I've been Googling a bit for a general error handling approach and can't find anything really useful. Basically if any ...

I’m currently writing my first batch file for deploying an asp.net solution.
I’ve been Googling a bit for a general error handling approach and can’t find anything really useful.

Basically if any thing goes wrong I want to stop and print out what went wrong.

Can anyone give me any pointers?

John Saunders's user avatar

John Saunders

160k26 gold badges240 silver badges393 bronze badges

asked Jul 22, 2009 at 9:15

handles's user avatar

I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.

yourCommand && (
  echo yourCommand was successful
) || (
  echo yourCommand failed
)

There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.

yourCommand && (
  someCommandThatMayFail
) || (
  echo This will fire if yourCommand or someCommandThatMayFail raises an error
)

The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call ), which does nothing except set the ERRORLEVEL to 0. There is a corollary (call) that does nothing except set the ERRORLEVEL to 1.

yourCommand && (
  someCommandThatMayFail
  (call )
) || (
  echo This can only fire if yourCommand raises an error
)

See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.

Community's user avatar

answered Jun 13, 2013 at 11:27

dbenham's user avatar

dbenhamdbenham

126k28 gold badges245 silver badges384 bronze badges

7

Using ERRORLEVEL when it’s available is the easiest option. However, if you’re calling an external program to perform some task, and it doesn’t return proper codes, you can pipe the output to ‘find’ and check the errorlevel from that.

c:mypathmyexe.exe | find "ERROR" >nul2>nul
if not ERRORLEVEL 1 (
echo. Uh oh, something bad happened
exit /b 1
)

Or to give more info about what happened

c:mypathmyexe.exe 2&1> myexe.log
find "Invalid File" "myexe.log" >nul2>nul && echo.Invalid File error in Myexe.exe && exit /b 1
find "Error 0x12345678" "myexe.log" >nul2>nul && echo.Myexe.exe was unable to contact server x && exit /b 1

answered Aug 27, 2013 at 16:55

M Jeremy Carter's user avatar

1

Other than ERRORLEVEL, batch files have no error handling. You’d want to look at a more powerful scripting language. I’ve been moving code to PowerShell.

The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.

Right now, it looks like any time invested in learning and using PowerShell will be time well spent.

answered Jul 22, 2009 at 10:52

Brad Bruce's user avatar

Brad BruceBrad Bruce

7,5653 gold badges38 silver badges60 bronze badges

3

A successful ping on your local network can be trapped using ERRORLEVEL.

@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT

michaelb958--GoFundMonica's user avatar

answered Jul 9, 2013 at 13:38

Rob Davis's user avatar

Rob DavisRob Davis

611 silver badge1 bronze badge

I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output

command 1> file — Write the standard output of command to file

command 2> file — Write the standard error of command to file

answered Feb 6, 2015 at 15:36

TakenItEasy's user avatar

Python Unittest, Bat process Error Codes:

if __name__ == "__main__":
   test_suite = unittest.TestSuite()
   test_suite.addTest(RunTestCases("test_aggregationCount_001"))
   runner = unittest.TextTestRunner()
   result = runner.run(test_suite)
   # result = unittest.TextTestRunner().run(test_suite)
   if result.wasSuccessful():
       print("############### Test Successful! ###############")
       sys.exit(1)
   else:
       print("############### Test Failed! ###############")
       sys.exit()

Bat codes:

@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
  echo Error found. Waiting here...
  pause
) || (
  echo This time of test is ok.
)
)

answered Sep 24, 2017 at 7:54

Tonny's user avatar

TonnyTonny

212 bronze badges

Its extremely easy!
Create a file that contains:

call <filename>  // the file you made
cls
echo An error occured!
<Your commands>
pause

So now when you start it, it will launch your program as normal. But when anything goes wrong it exits and continues the script inside the first file. Now there you can put your own commands in.

answered Nov 17, 2016 at 19:51

BlazeLP's user avatar

BlazeLPBlazeLP

1351 silver badge8 bronze badges

0

Поделиться

Нашли опечатку?

Пожалуйста, сообщите об этом — просто выделите ошибочное слово или фразу и нажмите Shift Enter.

Как правильно обрабатывать коды возврата из программ с помощью ERRORLEVEL Печать

Добавил(а) microsin

  

Раньше я не знал, как правильно использовать в командных файлах (расширение .bat) ERRORLEVEL вместе с оператором ветвления IF. Из-за этого у меня возникали ошибки при написании командных файлов.

Статья была переписана после того, как мне в комментарии указали на ошибку. В справке по команде (см. help if) подробно описывается алгоритм работы IF ERRORLEVEL. Команда предназначена для анализа кода возврата последней запущенной из bat-файла программы, и предпринимать по их значениям нужные действия. Чтобы команда работала правильно, нужно начинать проверять коды возврата с наибольших возможных значений, например так:
program0_4.exe
if errorlevel 4 goto error4
if errorlevel 3 goto error3
if errorlevel 2 goto error2
if errorlevel 1 goto error1
goto ok

Есть также возможность прямой проверки значения кода возврата, если использовать в командном файле переменную %ERRORLEVEL% (работает только в том случае, если Вы не умудрились задать переменную окружения с таким же именем). Переменная %ERRORLEVEL% разворачивается в текстовое значение кода возврата, что в позволяет использовать в командном файле конструкции типа:
goto answer%ERRORLEVEL%
:answer0
echo Получен код возврата 0
:answer1
echo Получен код возврата 1

 

Старый текст статьи

ERRORLEVEL 0 в командных файлах отрабатывается неправильно 

Предположим, программа program0_4.exe на выходе выдает коды возврата от 0 до 4, и код возврата 0 означает, что ошибок не было. Нужно отфильтровать оператором if факт отсутствия ошибки. В этом случае нельзя использовать проверку if errorlevel 0, так как результат этой проверки не всегда верен. Пример1 не работает, а Пример2 работает нормально.

rem Пример 1 — почему-то иногда НЕ РАБОТАЕТ
program0_4.exe
if errorlevel 0 goto ok
echo «Error!»
goto exit

:ok
echo «O.K.»

:exit

rem Пример 2 — работает нормально
program0_4.exe
if errorlevel 1 goto error
if errorlevel 2 goto error
if errorlevel 3 goto error
if errorlevel 4 goto error
goto ok

:ok
echo «O.K.»
goto exit

:error
echo «Error!»

:exit

Добавить комментарий

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.

An equivalent for the exit code $? in batch is the errorlevel accessible via the variable %ERRORLEVEL%. In batch scripting, there exists a special form of the IF-clause that uses the errorlevel: IF ERRORLEVEL n is equivalent to: «if the errorlevel is greater or equal to n«. As in bash, a value of 0 means the previous command executed without errors (not always, some commands don’t set the errorlevel). So you have two choices:

  1. IF %ERRORLEVEL% NEQ 0 which is the literal translation of your if-statement in your bash script. Be aware you’ll have to use the delayed expansion version IF !ERRORLEVEL! NEQ 0 inside code blocks delimited with (...) (check this question that explains why)
  2. IF ERRORLEVEL 1 which is IMHO more suitable (depends on your preferences though). Also works inside (...) code blocks but assumes commands never set negative errorlevels (never encountered one but is worth mentionning)

Normally setting a variable with the set command doesn’t change the errorlevel so you can choose either one of the two options. But as I don’t have a windows machine to test it right now, I’ll play it safe and give you the first option. I’ll edit my answer once I’ve tested the second option.

set exit_code=%ERRORLEVEL%
if %exit_code% NEQ 0 (  
    echo Error calling sqlplus, return code = %exit_code%
    exit /b %exit_code%
)

Some last advice: use exit /b
instead of exit. exit will also exit the command line in batch

EDIT I’ve tested the second version and it works as well. So the code above can be replaced with:

set exit_code=%ERRORLEVEL%
IF ERRORLEVEL 1 (  
    echo Error calling sqlplus, return code = %exit_code%
    exit /b %exit_code%
)

This blog article explains quite well why this version should be used instead of the of the first one using the %ERRORLEVEL% variable.

Another option @aschipfl kindly reminded me of in his comment is the use of the conditional executions operators && and ||:

  • command1 && command2 will execute command2 only if command1 succeeded
  • command1 || command2 will execute command2 only if command1 failed.

Both operators use the exit code (in most cases the same as errorlevel but not always) to determine if a command failed or succeeded.

I’ve also seen you’ve posted your batch-file. There is a little something I’d like to point out though: goto @ERROR_HANDLING_SQL will throw an error because there is no label @ERROR_HANDLING_SQL. There exists a label ERROR_HANDLING_SQL at the end of your script though. If you were trying to jump to that label you should replace all occurences of goto @ERROR_HANDLING_SQL with goto ERROR_HANDLING_SQL

An equivalent for the exit code $? in batch is the errorlevel accessible via the variable %ERRORLEVEL%. In batch scripting, there exists a special form of the IF-clause that uses the errorlevel: IF ERRORLEVEL n is equivalent to: «if the errorlevel is greater or equal to n«. As in bash, a value of 0 means the previous command executed without errors (not always, some commands don’t set the errorlevel). So you have two choices:

  1. IF %ERRORLEVEL% NEQ 0 which is the literal translation of your if-statement in your bash script. Be aware you’ll have to use the delayed expansion version IF !ERRORLEVEL! NEQ 0 inside code blocks delimited with (...) (check this question that explains why)
  2. IF ERRORLEVEL 1 which is IMHO more suitable (depends on your preferences though). Also works inside (...) code blocks but assumes commands never set negative errorlevels (never encountered one but is worth mentionning)

Normally setting a variable with the set command doesn’t change the errorlevel so you can choose either one of the two options. But as I don’t have a windows machine to test it right now, I’ll play it safe and give you the first option. I’ll edit my answer once I’ve tested the second option.

set exit_code=%ERRORLEVEL%
if %exit_code% NEQ 0 (  
    echo Error calling sqlplus, return code = %exit_code%
    exit /b %exit_code%
)

Some last advice: use exit /b
instead of exit. exit will also exit the command line in batch

EDIT I’ve tested the second version and it works as well. So the code above can be replaced with:

set exit_code=%ERRORLEVEL%
IF ERRORLEVEL 1 (  
    echo Error calling sqlplus, return code = %exit_code%
    exit /b %exit_code%
)

This blog article explains quite well why this version should be used instead of the of the first one using the %ERRORLEVEL% variable.

Another option @aschipfl kindly reminded me of in his comment is the use of the conditional executions operators && and ||:

  • command1 && command2 will execute command2 only if command1 succeeded
  • command1 || command2 will execute command2 only if command1 failed.

Both operators use the exit code (in most cases the same as errorlevel but not always) to determine if a command failed or succeeded.

I’ve also seen you’ve posted your batch-file. There is a little something I’d like to point out though: goto @ERROR_HANDLING_SQL will throw an error because there is no label @ERROR_HANDLING_SQL. There exists a label ERROR_HANDLING_SQL at the end of your script though. If you were trying to jump to that label you should replace all occurences of goto @ERROR_HANDLING_SQL with goto ERROR_HANDLING_SQL


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.

m9yt

19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

1

24.12.2015, 17:07. Показов 33257. Ответов 20

Метки нет (Все метки)


Привет всем!
Столкнулся с проблемой обработки значения errorlevel.
Вызываю внешний скрипт
call script1.bat %параметры%

Внутри script1.bat точно меняется значение errorlevel, становится отличным от 0 (ввожу неверные логин и пароль для подключения к схеме в sqlplus).
Проверял это, выводя значение с помощью echo.
Как только управление возвращается к внешнему батнику, то errorlevel почему-то обнуляется:

Windows Batch file
1
2
3
4
5
if %errorlevel% equ 0 (
  echo Connection successfully completed!
) else (
    Connection not complete!
  )

Т.е. всегда выводится первое сообщение, независимо от введенных данных.
Подскажите, как правильно передать значение errorlevel из script1.bat во внешний скрипт?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



10565 / 5529 / 864

Регистрация: 07.04.2013

Сообщений: 15,660

24.12.2015, 17:12

2

Windows Batch file

if errorlevel 0 (echo 0) else (echo not 0)



0



19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 17:15

 [ТС]

3

vavun, не понял, что Вы имеете ввиду?



0



10565 / 5529 / 864

Регистрация: 07.04.2013

Сообщений: 15,660

24.12.2015, 17:17

4

m9yt, весь батник покажите.



0



m9yt

19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 17:21

 [ТС]

5

Основной батник(не полный текст, только основное):

Windows Batch file
1
2
3
4
5
6
7
8
9
echo off 
cls
SETLOCAL ENABLEDELAYEDEXPANSION
call TOOLSConnectionCheckConnectionCheck.bat %SERVER% %SCHEMA% %SCHEMA_PASS%
if %errorlevel% equ 0 (
  echo Connection successfully completed!
) else (
    echo Connection not completed!
  )

ConnectionCheck.bat:

Windows Batch file
1
2
3
4
5
6
7
8
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION 
set SERVER=%1
shift
set SCHEMA=%1
shift
set SCHEMA_PASS=%1
sqlplus.exe -S -L %SCHEMA%/%SCHEMA_PASS%@%SERVER% @TOOLSScriptsInstallConnectionCheck.sql

Внутри ConnectionCheck.sql 1 оператор — exit;

Если вызывать проверку errorlevel внутри ConnectionCheck, то идет в нужные ветки.



0



vavun

10565 / 5529 / 864

Регистрация: 07.04.2013

Сообщений: 15,660

24.12.2015, 17:32

6

Основной

Windows Batch file
1
2
3
4
5
6
7
echo off 
call TOOLSConnectionCheckConnectionCheck.bat %SERVER% %SCHEMA% %SCHEMA_PASS%
if errorlevel 0 (
  echo Connection successfully completed!
) else (
    echo Connection not completed!
  )

ConnectionCheck.bat
Восьмая строка

Windows Batch file
8
sqlplus.exe -S -L %SCHEMA%/%SCHEMA_PASS%@%SERVER% @TOOLSScriptsInstallConnectionCheck.sql && exit /b 0 || exit /b 1

Добавлено через 5 минут
Зачем вам вообще ConnectionCheck.bat ?
Запишите все в основной



0



19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 17:34

 [ТС]

7

vavun, не помогло.

Насчет писать в основной — была такая идея. Но хочу разобраться, почему не работает этот вариант.



0



vavun

10565 / 5529 / 864

Регистрация: 07.04.2013

Сообщений: 15,660

24.12.2015, 17:45

8

Странно. Должен работать.

Либо у sqlplus.exe какие то особенности.

запишите это в основной вместо call TOOLSConnectionCheckConnectionCheck.bat

Windows Batch file
1
sqlplus.exe -S -L %SCHEMA%/%SCHEMA_PASS%@%SERVER% @TOOLSScriptsInstallConnectionCheck.sql && echo Connection successfully established! || echo Connection failed!

Что выдаст echo в случае успеха и в случае ошибки



0



m9yt

19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 18:00

 [ТС]

9

vavun,

Windows Batch file
1
@TOOLSScriptsInstallConnectionCheck.sql && echo Connection successfully established! || echo Connection failed!

в основном скрипте работает, как надо.
В любом случае, спасибо за помощь!



0



vavun

10565 / 5529 / 864

Регистрация: 07.04.2013

Сообщений: 15,660

24.12.2015, 18:21

10

m9yt, мне тут умный человек подсказал, что я ошибся кое где.

Надо так

Windows Batch file

if not errorlevel 1

или ваш вариант, он был верным.

Windows Batch file
1
if %errorlevel% equ 0

НО !

&& exit /b 0 || exit /b 1 должно быть обязательно, ибо именно это устанавливает errorlevel

Тоесть восьмая строка, как я уже писал, была сделана верно

Windows Batch file
8
sqlplus.exe -S -L %SCHEMA%/%SCHEMA_PASS%@%SERVER% @TOOLSScriptsInstallConnectionCheck.sql && exit /b 0 || exit /b 1


а if %errorlevel% equ 0
изначально был верным ваш

Вроде больше ничего не напутал



1



m9yt

19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 18:21

 [ТС]

11

Вернусь к теме.
Не написал про одну важную вещь.
Запуск sqlplus сопровождался и вызовом еще 1 скрипта:

Windows Batch file
1
sqlplus.exe -S -L %SCHEMA%/%SCHEMA_PASS%@%SERVER% @TOOLSScriptsInstallConnectionCheck.sql | cscript TOOLSForLOG.js >> "file.log"

Убрав эту 2 часть, все заработало. Походу, этот скрипт обнуляет переменную.
Как в таком случаем поступить?



0



10565 / 5529 / 864

Регистрация: 07.04.2013

Сообщений: 15,660

24.12.2015, 18:23

12

Цитата
Сообщение от m9yt
Посмотреть сообщение

Походу, этот скрипт обнуляет переменную.

Похоже на правду, но я уже запутался



0



19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 18:31

 [ТС]

13

Прошу помощи еще раз, если не затруднит)
Весь день убил на это, очень уж охота решить проблему!



0



10565 / 5529 / 864

Регистрация: 07.04.2013

Сообщений: 15,660

24.12.2015, 18:36

14

Цитата
Сообщение от m9yt
Посмотреть сообщение

Не написал про одну важную вещь.

Цитата
Сообщение от m9yt
Посмотреть сообщение

не полный текст, только основное

Вот лучше выложите все

полностью

, только без паролей, и детально опишите, что происходит, и что должно происходить.



0



m9yt

19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 19:29

 [ТС]

15

vavun,

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
echo off 
cls
SETLOCAL ENABLEDELAYEDEXPANSION 
set SERVER=
set SCHEMA=
set SCHEMA_PASS=
 
rem Задаем данные для подключения
set /P SERVER="Input server: "
 
set /P SCHEMA="Input schema: "
 
set /P SCHEMA_PASS="Input password for %SCHEMA%: "
 
rem Создаем каталог для логирования
set LOG_FOLDER=OUTLOG123
if not exist %LOG_FOLDER% (
  mkdir "%LOG_FOLDER%"
)
echo Log in "file.log" 
 
rem Вызываем sqlplus, где в ConnectionCheck.sql содержится только "exit;" При этом вызываем скрипт, который складывает поток от sqlplus в файл
sqlplus.exe -S -L %SCHEMA%/%SCHEMA_PASS%@%SERVER% @SRVTOOLSScriptsInstallConnectionCheck.sql | cscript SRVTOOLSForLOG.js >> "file.log"
if %errorlevel% equ 0 ( 
  echo Connection successfully established 
) else ( 
    echo Connection failed 
  )
  
pause

ForLOG.js:

Javascript
1
2
3
4
5
6
while (!WScript.StdIn.AtEndOfStream)
{
var wrstr = WScript.StdIn.ReadLine();
WScript.StdOut.WriteLine(wrstr);
WScript.StdErr.WriteLine(wrstr);
}

Добавлено через 8 минут
Убираю этот кусок из 23 строки:

Windows Batch file
1
| cscript SRVTOOLSForLOG.js >> "file.log"

и все работает как надо.

Добавлено через 32 минуты
Согласен оставить:

Windows Batch file
1
sqlplus.exe -S -L %SCHEMA%/%SCHEMA_PASS%@%SERVER% @SRVTOOLSScriptsInstallConnectionCheck.sql

И писать в лог-файл отдельно каждую нужную мне строку по проверке подключения:

Windows Batch file
1
2
3
4
5
if %errorlevel% equ 0 ( 
  echo Connection successfully established | cscript SRVTOOLSForLOG.js >> "file.log"
) else ( 
    echo Connection failed | cscript SRVTOOLSForLOG.js >> "file.log"
  )

Но нужно решить проблему с тем, что каждый вызов скрипта ForLOG.js вначале пишет и информацию о cscript, которая появляется при его запуске:
Сервер сценариев Windows (Microsoft R) версия 5.8
c Корпорация Майкрософт (Microsoft Corp.), 1996-2001. Все права защищены.



0



3455 / 1993 / 635

Регистрация: 26.02.2014

Сообщений: 1,457

24.12.2015, 19:35

16

Лучший ответ Сообщение было отмечено vavun как решение

Решение

Цитата
Сообщение от m9yt
Посмотреть сообщение

Но нужно решить проблему с тем, что каждый вызов скрипта ForLOG.js вначале пишет и информацию о cmd-файле, которая появляется при его запуске:
Microsoft Windows [Version 6.1.7601]
(c) Корпорация Майкрософт (Microsoft Corp.), 2009. Все права защищены.

Windows Batch file

cscript //nologo SRVTOOLSForLOG.js >> "file.log"



1



19 / 3 / 1

Регистрация: 17.11.2009

Сообщений: 139

24.12.2015, 19:39

 [ТС]

17

ComSpec, спасибо!



0



Эксперт WindowsАвтор FAQ

17954 / 7591 / 889

Регистрация: 25.12.2011

Сообщений: 11,323

Записей в блоге: 17

29.12.2015, 21:11

18

Цитата
Сообщение от m9yt
Посмотреть сообщение

Насчет писать в основной — была такая идея. Но хочу разобраться, почему не работает этот вариант.

Потому что завершение дочернего скрипта без явного указания кода возврата (в вашем случае: exit /b %errorlevel%), автоматически означает установку кода успеха — 0.



0



1 / 1 / 0

Регистрация: 12.06.2015

Сообщений: 67

11.12.2018, 18:04

19

Вопрос.
.
Как в ECHO вывести строку вот такую строку «%ERRORLEVEL%» (НЕ значение %ERRORLEVEL%) ?
Именно строку «%ERRORLEVEL%» , А НЕ ЗНАЧЕНИЕ переменной %ERRORLEVEL% .
.
Вариант
ECHO ^%ERRORLEVEL^% НЕ работает !!!
.



0



4330 / 2120 / 661

Регистрация: 26.04.2015

Сообщений: 6,823

11.12.2018, 18:17

20

удвоить % — %%



1



Понравилась статья? Поделить с друзьями:
  • Bass slapper encountered an error while loading samples
  • Bass error fileopen
  • Bass error 2 in loadmedia
  • Basic ios clear iostream error
  • Basic error controller spring