I am trying to query each instance on my CMS. But why the errorlevel is still 0 when I tested the stopped instance? And how can I skip the last line in my Instance_list.txt (The %%a will be '(44')
:Start
REM get the full list of our instance from CMS to Instance_list.txt
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd" -S cms_instance -e -d msdb -Q "SELECT DISTINCT server_name FROM sysmanagement_shared_registered_servers_internal" -o Instance_list.txt
:Run
REM Run query against all instances one by one.
#echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2 skip=3" %%a in (Instance_list.txt) do (
Set Intance_NAME=%%a
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd" -S !Intance_NAME! -e -d master -Q "SELECT ##SERVERNAME" -o SQL_result.txt
TIMEOUT /T 2
FINDSTR "!Intance_NAME!" SQL_result.txt
IF %ERRORLEVEL% NEQ 0 (
ECHO SQL INSTANCE !Intance_NAME! HAS SOME ISSUE...
)
)
This is a SQLCMD FAQ. You need to set the -b switch for sqlcmd to set the ERRORLEVEL
-b Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an error occurs. The value that is returned to the DOS ERRORLEVEL
variable is 1 when the SQL Server error message has a severity level
greater than 10; otherwise, the value returned is 0. If the -V option
has been set in addition to -b, sqlcmd will not report an error if the
severity level is lower than the values set using -V. Command prompt
batch files can test the value of ERRORLEVEL and handle the error
appropriately. sqlcmd does not report errors for severity level 10
(informational messages).
https://learn.microsoft.com/en-us/sql/tools/sqlcmd-utility?view=sql-server-2017
Related
I am working on a batch file that calls 4 other batch files. If the sub-batch file returns with an errorlevel code other than 0, I want the parent batch file to capture it, send out an email and exit the parent batch file. However, as soon as the first child batch file is called and returns with a non-zero errorlevel, none of the subsequent commands in the parent batch file run. Here is my batch code:
rem ** setup so it logs itself **
set parent=%~dp0
set me=%~n0
set LOGFILE=%parent%logs\%me%.log 2>&1
if exist "%LOGFILE%" del %LOGFILE% /f /s /q
call :LOG > %LOGFILE%
exit
:LOG
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS EnableDelayedExpansion
echo ParentDir: %parent%
echo ProgramName: %me%
echo.
rem ** script variables **
set batFile1=%parent%FILE1.bat
set batFile2=%parent%FILE2.bat
set batFile3=%parent%FILE3.bat
set batFile4=%parent%FILE4.bat
set FromEmail=server#domain.com
set Recipient=adminuser#domain.com
set CCRecipient=
set Subject=Email Subject
set Message=There was an error in running nightly batch files. Please look at the logs to determine which batch file is causing a problem. \n\nAt your service\nAdmin
set Server=smtp.domain.com
set Port=25
rem ** run bat files and capture error message **
echo.
echo Start: Send Email
set Message=Debug test code
c:\APPS\sendemail.exe -f %FromEmail% -t %Recipient% -cc %CCRecipient% -u "%Subject%" -m "%Message%" -v -s %Server%
call %batFile1%
set exitcode=%ERRORLEVEL%
echo %exitcode%
echo.
echo Start: Send Email
set Message=Debug test code !exitcode!
c:\APPS\sendemail.exe -f %FromEmail% -t %Recipient% -cc %CCRecipient% -u "%Subject%" -m "%Message%" -v -s %Server%
if %exitcode% NEQ 0 (
echo.
set Message=Execution of !batFile1! failed with error message !errorcode!. Examine the logs and fix any issues before next run.\n\nAt your service\nAdmin
echo Start: Send Email
c:\APPS\sendemail.exe -f !FromEmail! -t !Recipient! -cc !CCRecipient! -u "!Subject!" -m "!Message!" -v -s !Server!
rem ** force execution to quit if check fails
EXIT /B %ERRORLEVEL%
)
call %batFile2%
if %ERRORLEVEL% NEQ 0 (
echo.
set Message=Execution of %batFile2% failed with error message %ERRORLEVEL%. Examine the logs and fix any issues before next run.\n\nAt your service\nAdmin
echo Start: Send Email
c:\APPS\sendemail.exe -f %FromEmail% -t %Recipient% -cc %CCRecipient% -u "%Subject%" -m "%Message%" -v -s %Server%
rem ** force execution to quit if check fails
EXIT /B %ERRORLEVEL%
)
call %batFile3%
if %ERRORLEVEL% NEQ 0 (
echo.
set Message=Execution of %batFile3% failed with error message %ERRORLEVEL%. Examine the logs and fix any issues before next run.\n\nAt your service\nAdmin
echo Start: Send Email
c:\APPS\sendemail.exe -f %FromEmail% -t %Recipient% -cc %CCRecipient% -u "%Subject%" -m "%Message%" -v -s %Server%
rem ** force execution to quit if check fails
EXIT /B %ERRORLEVEL%
)
call %batFile4%
if %ERRORLEVEL% NEQ 0 (
echo.
set Message=Execution of %batFile4% failed with error message %ERRORLEVEL%. Examine the logs and fix any issues before next run.\n\nAt your service\nAdmin
echo Start: Send Email
c:\APPS\sendemail.exe -f %FromEmail% -t %Recipient% -cc %CCRecipient% -u "%Subject%" -m "%Message%" -v -s %Server%
rem ** force execution to quit if check fails
EXIT /B %ERRORLEVEL%
)
EXIT /B %ERRORLEVEL%
It appears that none of the lines of code are executed that follow the command call %batFile1%
For information purposes, this is how the %batFile1% exits:
EXIT /B 254
so that should be coming back with %ERRORLEVEL% 254 every time. the test email that I send just before calling batFile1 works fine.
#echo off
setlocal EnableExtensions
rem ** setup so it logs itself **
set "parent=%~dp0"
set "me=%~n0"
set "LOGFILE=%parent%logs\%me%.log"
if exist "%LOGFILE%" del "%LOGFILE%" /f /s /q
call :LOG > "%LOGFILE%" 2>&1
exit
:LOG
setlocal
echo ParentDir: %parent%
echo ProgramName: %me%
echo.
rem ** script variables **
set batFiles="%parent%FILE1.bat" "%parent%FILE2.bat" "%parent%FILE3.bat" "%parent%FILE4.bat"
set "FromEmail=server#domain.com"
set "Recipient=adminuser#domain.com"
set "CCRecipient="
set "Subject=Email Subject"
set Message=There was an error in running nightly batch files.^
Please look at the logs to determine which batch file is causing a problem.\n\n^
At your service\n^
Admin
set "Server=smtp.domain.com"
set "Port=25"
rem ** Send email test **
echo.
echo Start: Send Email
set Message=Debug test code
c:\APPS\sendemail.exe -f "%FromEmail%" -t "%Recipient%" -cc "%CCRecipient%" -u "%Subject%" -m "%Message%" -v -s "%Server%"
rem ** run bat files and capture error message **
for %%A in (%batFiles%) do (
call :EMAIL %%A
if errorlevel 1 exit /b
)
exit /b
:EMAIL
setlocal
echo.
call "%~1"
if errorlevel 1 (
echo %errorlevel%
set "exitcode=%errorlevel%"
) else exit /b
rem ** Send email **
if "%~n1" == "FILE1" (
set "Message=Debug test code %exitcode%"
) else set Message=Execution of '%~1' failed with error message %exitcode%.^
Examine the logs and fix any issues before next run.\n\nAt your service\nAdmin
echo Start: Send Email
c:\APPS\sendemail.exe -f "%FromEmail%" -t "%Recipient%" -cc "%CCRecipient%" -u "%Subject%" -m "%Message%" -v -s "%Server%"
rem ** force execution to quit if check fails **
if %errorlevel% neq 0 echo Email send error message %errorlevel%.
exit /b
With optimizing the code some, to remove duplication etc.
It appears to be working better. I may have accidently fixed it.
Suggest checking echo %errorlevel% of the call before using
set, else %errorlevel% is of the set command.
None of the new code requires delayed expansion, so remove the
EnableDelayedExpansion setting.
Scripts are set to one variable and is used as a file-set,
in a for loop.
Many of set variable=value are double quoted to avoid any
trailing space issues. Those not, are multiline etc. that
are better without.
The Send Email code is not in a label :EMAIL which helped
to merge the duplicate code. It does a check if name FILE1
is the argument and uses a different email message to match
your original code.
It will end the script if sendemail.exe sets %errorlevel%
to not zero, which is later checked in the for loop.
If you want to exit on the called child batch-file instead,
change the last line from exit /b to exit /b %exitcode%.
Note, implicit use of exit /b is same as exit /b %errorlevel%.
If you prefer the later, update the code to you preference.
The later may require delayed variable expansion if used
in a code block i.e. (command & exit /b !errorlevel!).
When I run the below batch file code, it thinks that the server address is 'dbuser' and the Database is 'False'
What am I doing wrong?
Here is the code:
#echo off
set toolspath=C:\Program Files (x86)\Folder\Application
Set ApplicationServer=00.0.00.000
Set ApplicationDatabase=dbApplication
Set ApplicationUser=dbuser
Set ApplicationPassword=abcdefg
Set ApplicationUpgradeFromPre12_5=False
REM echo "Attaching dbApplication .. "
REM osql -S %ApplicationServer% -U %ApplicationUser% -P %ApplicationPassword% -i %ApplicationScriptsPath%\AttachApplicationDatabase.sql
REM osql -S %ApplicationServer% -U %ApplicationUser% -P %ApplicationPassword% -i %ApplicationScriptsPath%\SetDBVersion.sql
REM echo "Done."
call ApplicationUpgradeScripts.bat %%2 %ApplicationUser% %ApplicationPassword% %ApplicationDatabase% %ApplicationUpgradeFromPre12_5%
#if ERRORLEVEL 1 goto ERRORSEXIT
#Echo %ApplicationDatabase% Database Updated Successfully.
goto FINISH
:ERRORSEXIT
#Echo Error: Database Excecuted With Error. To Find out Exact Error see file ErrorLog.log
exit /B 1
goto ENDBUILD
:FINISH
#Echo All Databases Excecuted Successfully.
exit 0
:ENDBUILD
pause
I'm using SQLCMD to get the count of rows in a table, but I also want to be aware if the query hits an error.
The sqlcmd I'm using looks like this:
sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%"
If it works, it will return:
-----------
10205
(1 rows affected)
(Note, there is a blank line above the ------- for the column name I'm not specifying.)
If I pass in a table that doesn't exist, I get the following response:
Msg 208, Level 16, State 1, Server devServer, Line 1
Invalid object name 'dbo.no_table'.
Since I have the -b flag, I can check ERRORLEVEL for a value (in this case, 1).
To store the count variable, I've been using the following line:
for /F %%i in ('sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%" ^| findstr /r "[^(][0-9]"') do SET /a rec_count=%%i
After the for, %errorlevel% returns 0. Even inside the do, errorlevel is 0.
Is there any simple way to run sqlcmd, store the count if there is not an error, and print both lines if there is an error?
Commands that are executed by FOR /F are implicitly executed via a new CMD session. For example, with for /f %a in ('echo hello') do ..., the command that is executed becomes C:\Windows\system32\cmd.exe /c echo hello.
Your command is properly setting the ERRORLEVEL, but then the value is lost as soon as the child CMD session terminates and control is returned to your batch script.
So the /b option is not really doing any good for you, and can be dropped.
You can suppress the header info by adding the -h -1 option.
You can suppress the (1 rows affected) message by prefixing your command with set nocount on;
You can add the -r 1 option to cause error messages to appear on stderr instead of stdout. This will prevent FOR /F from processing any error, and the error message will appear on the screen instead.
You can clear the rec_count variable before you execute the command. Then it will remain undefined if there was an error, else it will contain the count if there was no error.
set "rec_count="
for /f %%A in (
'sqlcmd -S %server% -U %user% -P %pass% -h -1 -r 1 -Q "set nocount on;select count(*) from %table%"'
) do set "rec_count=%%A"
if not defined rec_count echo There was an error!
One other thing you might consider is using environment variables recognized by SQLCMD for your server, username, and password. Then you won't have to use the -S, -U, or -P options. This is especially handy if your batch script runs many SQLCMD commands.
set "sqlcmdServer=YourServer"
set "sqlcmdUser=YourUserName"
set "sqlcmdPassword=YourPassword"
set "rec_count="
for /f %%A in (
'sqlcmd -h -1 -r 1 -Q "set nocount on;select count(*) from %table%"'
) do set "rec_count=%%A"
if not defined rec_count echo There was an error!
The reason errorlevel does not seem to be getting set is because the for command is executing successfully, regardless of how the code that it loops through executes. So you can only interact with the errorlevel that is set by the sqlcmd command on the same line (inside the for loop brackets).
You should be able to use || (double pipe) after the sqlcmd command. Any code after || will only run if the previous command fails. Example:
notACommand || echo test
Will return "test". While the following will output only "a command":
echo a command || echo test
I can't test it, but something like the following should work for you:
for /F "EOL=(" %%i in ('sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%" ^|^| echo fail') do (
SET rec_count=%%i
)
if "%rec_count%"=="fail" echo SQL command failed
If the output is exactly as you say, then you should not need the findstr command - just set ( open bracket as an EOL character in the for loop, so you effectively drop the "(1 rows affected)" line. You will probably want to use the variables differently, but this is just one way you can tell if the sqlcmd command has failed or not.
As for outputting the error - a bad solution is to run the same sqlcmd command again. Something like the following:
set command=sqlcmd -S %server% -U %user% -P %pass% -b -Q "select count(*) from %table%"
for /F "EOL=(" %%i in ('%command% ^|^| echo fail') do SET rec_count=%%i
if "%rec_count%"=="fail" (%command%) else echo rec_count is %rec_count%
Note that I removed the /a switch when setting the rec_count variable, because it can now be set as a word.
I have written a small batch file to connect 15 SQL Servers via sqlcmd and store the output of the t-sql query in an HTML format output file. The script runs fine when all SQL Servers are up and running, but whenever any one of SQL Server is down then following error get saved in output file - "HResult 0xFFFFFFFF, Level 16, State 1 SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. "
Instead of writing such vague error, I tried to write error handler for connection failure using IF ELSE also but it didn't worked out, need help.
Part of code I tried to write for error handling (if SQL instance is down) is as below, the input text file contains following two values for all sql servers --> SQLinstancename,Application name
FOR /F "tokens=1,2 delims=," %%G in (%CD%\SQLServerList_SQLReport.txt) DO (
sqlcmd -E -S %%G -q "exit(select ##servername)"
IF ERRORLEVEL==0 (
sqlcmd -E -S %%G -i %MainSCRIPT% -v appname = "%%H" >> %HTMLFILE%
) ELSE (
ECHO "<tr><tr rowspan=1><td align=center bgcolor = gray rowspan=1><b><font face=verdana color=white size=1>%%H</font></b></td>" >> %HTMLFILE%
ECHO "<td align=center rowspan=1><font face=verdana size=1>%%G</font></td>" >> %HTMLFILE%
ECHO "<td align=center colspan =6 rowspan=1><font face=verdana size=1 color=RED><b>Unable to connect to SQL Server, check the connectivity*</b></font><tr></tr><tr></tr>" >> %HTMLFILE%
))
You omitted the percent signs from the variable.
IF %ERRORLEVEL%==0 (
but in a loop you would be better off using this, which doesn't need percent signs or delayed expansion. You have to test this way because errorlevel 0 is always true.
if not errorlevel 1 (
Is it possible to have conditional statements in batch scripts?
For example:
I have two servers, S1 and S2.When the batch file is deployed in S1 then the output should be generated in location L1. Likewise if the batch file is deployed in S2 then output should be generated in location L2.
My script:
set ComputerName=S1
set RepServer=%ComputerName%
set DBServer=%ComputerName%
set ReportPath="/DEV/Clearviewbilling"
set SharedPath=\\scottvdr1\ClearviewBilling\DEV-TEST
set UserId=-E
set fn=Create_Log.txt
if exist %fn% del %fn%
#echo on
#rem Reports
rs -i "%CD%"\Reports\Create_Sub.rss -s http://%RepServer%/reportserver -v Path=%SharedPath% -v rootpath=%ReportPath% -v DBServer=%DBServer% -t >> %fn% 2>&1
But i want the script to be:
set ComputerName=S1
set RepServer=%ComputerName%
set DBServer=%ComputerName%
If ComputerName=S1
Set SharedPath=//blah/blah
else
Set sharedPath=//some/path
set ReportPath="/DEV/Clearviewbilling"
set UserId=-E
set fn=Create_Log.txt
if exist %fn% del %fn%
#echo on
#rem Reports
rs -i "%CD%"\Reports\Create_Sub.rss -s http://%RepServer%/reportserver -v Path=%SharedPath% -v rootpath=%ReportPath% -v DBServer=%DBServer% -t >> %fn% 2>&1
Hence when the file is deployed, the reports are generated in the required path. But this is not working.
You compare the string ComputerName against S1 with the wrong if-else syntax
This should work
if "%ComputerName%"=="S1" (
Set "SharedPath=//blah/blah"
) else (
Set "sharedPath=//some/path"
)