How to conditionally exit .BAT file from SQL code run through SQLCMD - tsql

I have a .bat (Windows command) file that includes invocations of SQLCMD and other commands. (Of course SQLCMD is sending my T-SQL code to SQL Server.) I want to detect certain conditions in the SQL code, and conditionally exit the entire batch file. I've tried various combinations of RAISERROR, THROW, and deliberate division by 0 (I'm not proud) along with various command line switches on SQLCMD and handling of errorlevel in the .bat file.
I tried the answer to 5789568 but could not get it to work in my case. Here are two files which show one failed attempt. It tries to abort if there are more than 3 tables. But it doesn't abort the bat file, as you can see when the final command (echo) executes. It doesn't even abort the run of SQLCMD, as you can see when it tells you how many tables there are.
example.bat
set ERRORLEVEL=0
sqlcmd -b -S dbread.vistaprint.net -E -d columbus -e -i example.sql
if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%
echo we got to the end of the BAT file
example.sql
SET XACT_ABORT ON
if ((SELECT COUNT(*) FROM sys.tables) > 3)
begin
RAISERROR ('There are more than 3 tables. We will try to stop', 18, -1)
end
SELECT COUNT(*) FROM sys.tables

%ERRORLEVEL% is not a normal environment variable. It is a dynamic pseudo variable that returns the current ERRORLEVEL. If you explicitly define a true environment variable with set ERRORLEVEL=0, then the dynamic nature is destroyed, and %ERRORLEVEL% will forever return the value of your user defined environment variable until you undefine your user value. You should never define your own values for ERRORLEVEL, RANDOM, CD, TIME, DATE etc.
If you want to clear the ERRORLEVEL, then you must execute a command that sets the value to 0. I like to use (call ).
Assuming there are no other problems with your code, it should be fixed with the following:
(call )
sqlcmd -b -S dbread.vistaprint.net -E -d columbus -e -i example.sql
if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%
echo we got to the end of the BAT file
sqlcmd is an external command (exe program), so it always sets ERRORLEVEL. Therefore you should not have to clear the ERRORLEVEL, and (call ) could be removed. You really only have to worry about clearing the ERRORLEVEL before you run internal commands that do not set ERRORLEVEL to 0 upon success. (See Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?)

#dbenson's answer solves the problem with the .bat file. But there is also a problem with the .sql file, whose symptom is that the last line executes despite the error. Here is a complete solution. That is, these two files work correctly.
The "error" for which the code is checking is that a database named 'master' exists. If you replace 'master' with something that is not the name of a database, it runs without error.
example.bat
REM Replace the server name with any SQL Server server to which you
REM have at least read access. The contents of the server don't matter.
sqlcmd -b -S dbread.vistaprint.net -E -i example.sql
if %errorlevel% neq 0 exit /b %errorlevel%
echo 'In the .bat file, we got past the error check, so run was successful.'
example.sql
if exists (select * from master.sys.databases where name = 'master')
begin
RAISERROR ('Found an error condition', 18, 10)
return
end
print 'In the SQL file, we got past the error check, so run was successful.'

Related

Set and execute a command from a function

How can I write a fish function that executes a command in a string and make it appear in the history?
function qh --description 'Use peco to query command history'
if test (count $argv) = 0
set peco_flags --layout=bottom-up
else
set peco_flags --layout=bottom-up --query "$argv"
end
history | peco $peco_flags | read cmd
if test $cmd
commandline $cmd
else
commandline ''
end
end
This does not work...
It is possible to create a key binding which sets the command line and then executes it; that command will then appear in history. Example:
function whatday
commandline "echo Today is $(date +%A)"
commandline -f execute
end
bind \eq whatday
now alt-q will set the commandline to echo Today is Sunday and execute it; it appears in history.
Beyond that there are also abbreviations which allow replacing tokens with text; but the text is just static (e.g. gco -> git checkout).
There is as yet no way for an arbitrary fish function (e.g. run as part of a shell script) to append to history, only delete and read from it.

User input as a command line argument

I have a program BIL.exe that prompts for user four inputs (marked with pink below).
I would like to run this program from command line by specifying the inputs as arguments. Something like this:
.\BIL.exe "HOAL" 78 80 1
In a batch script I can do it as shown below. However this doesn't work in command line.
#echo off
set var1="HOAL"
set var2=78
set var3=80
set var4=1
(echo %var1% && echo %var2% && echo %var3% && echo %var4%)|BIL.exe
Does the solution differ between CMD and powershell?
So given your confirmation that stdin from file worked means that the solution should be simple:
batch_name.cmd
#echo off
(echo %1&echo %2&echo %3&echo %4)|bil.exe
it sends the output in list format. so you should be able to run the batch as:
batch_name.cmd "HOAL" 78 80 1
keep in mind, I am not stripping outside quotations, as it seems that those are used by the executable. If not, then change to:
#echo off
(echo %~1&echo %~2&echo %~3&echo %~4)|bil.exe
As you never need to set anything in relation to the variable name, we simply do not use variables as they come as input meta variables from your input.

Batch Code to Skip Script if File is too Old

My Problem
As there are a ton of threads that address 'using a batch file to return file modify date' (or delete files older than, etc) - let me first specify my issue.
I'm looking to create a batch (not PowerShell, etc) that will return the last modify date of a specific file given UNC path and filename.
Code, Attempt 1
I've taken a peek at a few potential solutions on other threads, but I've run into a number of unique issues. The first and most obvious solution for this would be the "ForFiles" command in batch. For example:
set myPath=\\myUNCpath
set myFile=myFileName.csv
forfiles /p "%myPath%" /m %myFile% /c "GoTo OldFile" /d -6
Thus, if the file is older than I want -- jump to a specific section of my batch for that. However, this yields the error:
ERROR: UNC paths (\machine\share) are not supported.
However, this cmd won't work due to the use of UNC (which is critical as this batch is called by system's task scheduler). So it seems like the 'ForFiles' cmd is out.
Code, Attempt 2
I could go a more round about way of doing it, but simply retrieving the last modified date of the file (which in batch would return a string). I can truncate the string to the necessary date values, convert to a date, and then compare to current date. To do that, I've also looked into just using a for loop such as:
set myFile=\\myUNCpath\myFileName.csv
echo %myFile%
pause
FOR %%f IN (%myFile%) DO SET myFileDate=%%~tf
echo %myFileDate%
pause
Though my first debug echo provides the proper full file name, my second debug just returns ECHO is off., which tells me it's either not finding the file or the for loop isn't returning the file date. Not sure why.
I've also tried minor changes to this just to double check environmental variable syntax:
FOR %%f IN (%myFile%) DO SET myFileDate=%%~ta
Returns %ta
And finally:
FOR %%f IN (%myFile%) DO SET myFileDate=%~ta
Which without the extra '%', just crashes the batch.
I'm really at a loss at this point. So any tips or guidance would be greatly appreciated!
Using forfiles to a UNC path can be used using PushD
For just echoing the file older than x in UNC path, simply just use
PushD %myPath% &&(
forfiles -s -m %myFile% -d -6 -c "cmd /c echo /q #file
) & PopD
Here is one way how to use goto if file older than x found in UNC path using your examples.
if not exist "C:\temp" mkdir C:\temp
if not exist "C:\temp\test.txt" echo.>"c:\temp\test.txt"
break>"c:\temp\test.txt"
set myPath=\\myUNCpath
set myFile=myFileName.csv
PushD %myPath% &&(
forfiles -s -m %myFile% -d -6 -c "cmd /c echo /q #file >> c:\temp\test.txt"
) & PopD
for /f %%i in ("C:\temp\test.txt") do set size=%%~zi
if %size% gtr 0 goto next
:next
Huge thanks to both #Squashman and #MadsTheMan for the help. Luckily this batch finally is the piece of code that I can take to my boss to push switching over to at least using PowerShell!
Anyway, for those of you looking for the best way to get a UNC path file's modify date, here is what I've come up with. Not very different than other threads (and a thanks goes out to Squashman for spotting my missing " " in the for loop).
set myFile=\\myUNCpath\myFileName.ext
FOR %%f IN ("%myFile%") DO SET myFileDate=%%~tf
::And if you'd like to try to do long winded calculations you can further break the dates down via...
set fileMonth=%myFileDate:~0,2%
set fileDay=%myFileDate:~3,2%
set fileYear=%myFileDate:~6,4%
set currentDate=%date%
set currentMonth=%currentDate:~4,2%
set currentDay=%currentDate:~7,2%
set currentYear=%currentDate:~10,4%
The plan was to then convert the strings to integers, and then use a switch-case block to determine if the variance between dates was acceptable... blah blah blah.
Long story short - if you are limited to batch (and not creating secondary files -- such as a csv or the temp file suggested by MadsTheMan) you're going to have a really long script on your hands that still might have flaws (like leap year, etc unless you're adding even MORE code), when you could just make the comparison calculation using one line of code in other programs.

How can i use Relative or Environment variable in Batch command

I am running below command to run Soapui Test suite and it is working fine
testrunner.bat -s"TestSuite4" "D:\Invesco\JP Groovy Code\ExploreGroovy.xml"
I ahve also used with below command and it is working fine as well
testrunner.bat -s"TestSuite4" "%USERPROFILE%\ExploreGroovy.xml"
Now I have added one Envrionment variable 'EnvP' and its value id 'D:\Invesco' and tried with following command but it is not working.
testrunner.bat -s"TestSuite4" "%EnvP%\ExploreGroovy.xml"
Can some one help me in this. I don't want to give hard coded path of any drive. Please suggest if anyone has any other solution.
Thanks.
the process starting testrunner.bat (probably explorer.exe?) must
know about the new variable. have you tried logging out and in again
after setting it?
if it is cmd, try finding the variable with set | find "EnvP". If it is not there, you need to start a new cmd session.
Use these commands and you should see why it fails:
#echo "%EnvP%"
#if not exist "%EnvP%\ExploreGroovy.xml" #echo Ouch!
#pause
testrunner.bat -s"TestSuite4" "%EnvP%\ExploreGroovy.xml"
#pause
For all my SoapUI projects I have multiple .bat scripts in the same location as the project.xml file to run different sets of test suites, and all of it goes into your source repository.
IF NOT DEFINED SOAPUI_ROOT SET SOAPUI_ROOT=%ProgramFiles%\SmartBear\soapUI-Pro-4.6.4
REM make certain we are where we _think_ we are
CD %~dp0
REM cleanup previous results
DEL /f /q *.log*
RMDIR /s /q results
REM run the tests
CALL "%SOAPUI_ROOT%\bin\testrunner.bat" -s"Smoke TestSuite" -fresults My-soapui-project.xml
REM determine if there are failures
IF errorlevel 0 (
ECHO All tests passed.
PAUSE
EXIT 0
) ELSE (
ECHO There are failures!
PAUSE
EXIT 100
)

How to check in command-line if a given file or directory is locked (used by any process)?

I need to know that before any attempt to do anything with such file.
Not sure about locked directories (does Windows have that?)
But detecting if a file is being written to by another process is not difficult.
#echo off
2>nul (
>>test.txt echo off
) && (echo file is not locked) || (echo file is locked)
I use the following test script from another window to place a lock on the file.
(
>&2 pause
) >> test.txt
When I run the 2nd script from one window and then run the 1st script from a second window, I get my "locked" message. Once I press <Enter> in the 1st window, I get the "unlocked" message if I rerun the 1st script.
Explanation
Whenever the output of a command is redirected to a file, the file of course must be opened for write access. The Windows CMD session will attempt to open the file, even if the command does not produce any output.
The >> redirection operator opens the file in append mode.
So >>test.txt echo off will attempt to open the file, it writes nothing to the file (assuming echo is already off), and then it closes the file. The file is not modified in any way.
Most processes lock a file whenever they open a file for write access. (There are OS system calls that allow opening a file for writing in a shared mode, but that is not the default). So if another process already has "test.txt" locked for writing, then the redirection will fail with the following error message sent to stderr - "The process cannot access the file because it is being used by another process.". Also an error code will be generated upon redirection failure. If the command and the redirection succeed, then a success code is returned.
Simply adding 2>nul to the command will not prevent the error message because it redirects the error output for the command, not the redirection. That is why I enclose the command in parentheses and then redirect the error output to nul outside of the parens.
So the error message is effectively hidden, but the error code is still propagated outside of the parens. The standard Windows && and || operators are used to detect whether the command inside the parens was successful or failed. Presumably echo off will never fail, so the only possible reason for failure would be the redirection failed. Most likely it fails because of a locking issue, though technically there could be other reasons for failure.
It is a curious "feature" that Windows does not set the %ERRORLEVEL% dynamic variable to an error upon redirection failure unless the || operator is used. (See File redirection in Windows and %errorlevel%). So the || operator must read the returned error code at some low level, not via the %ERRORLEVEL% variable.
Using these techniques to detect redirection failure can be very useful in a batch context. It can be used to establish locks that allow serialization of multiple events in parallel processes. For example, it can enable multiple processes to safely write to the same log file at the "same" time. How do you have shared log files under Windows?
EDIT
Regarding locked folders. I'm not sure how Windows implements this, perhaps with a lock. But if a process has an active directory involving the folder, then the folder cannot be renamed. That can easily be detected using
2>nul ren folderName folderName && echo Folder is NOT locked || echo folder is LOCKED
EDIT
I have since learned that (call ) (with a space) is a very fast command without side effects that is guaranteed to succeed with ERRORLEVEL set to 0. And (call) (without a space) is a fast command without side effects that is guaranteed to fail with ERRORLEVEL 1.
So I now use the following to check if a file is locked:
2>nul (
>>test.txt (call )
) && (echo file is not locked) || (echo file is locked)
In addition to great answer from dbenham, the following form finally help me understand used technique:
( type nul >> file.txt ) 2>nul || echo File is locked!
type nul command gives an empty output and does not affect the current echo setting like echo off command in orginal.
If you want to use if–then–else condition remember of correct order - success statement (&&) is going first and alternate statement (||) is going second:
command && (echo Command is successful) || (echo Command has failed)
If you download and install the Windows Server 2003 Resource Kit Tools there is a utility called oh.exe that will list open file handles for a given file:
http://www.microsoft.com/en-us/download/details.aspx?id=17657
Once you install it, reboot your machine and you'll be able to use the utility. You can see all the options in the Help and Support center as well as by typing oh /? in the command prompt.
(Info from : http://windowsxp.mvps.org/processlock.htm )
Note, the writing of a message stating the file status was less helpful than a batch command that set a return code. For example, return code 1 if file is locked.
#echo off
2>nul (
>>test.tmp echo off
) && (EXIT /B 0) || (EXIT /B 1)
Other answers resulted in side-effects for me. For instance, the following from this answer will cause file watchers to trigger:
COPY /B app.exe+NUL app.exe
And the following from the top answer here would overwrite any changes made to the target file:
2>nul (
>>test.txt (call )
) && (echo file is not locked) || (echo file is locked)
On modern version of Windows, you can call into Powershell to accomplish this task with zero side-effects:
powershell -Command "$FileStream = [System.IO.File]::Open('%FILE%', 'Open', 'Write'); $FileStream.Close(); $FileStream.Dispose()" && (echo File is not locked) || (echo File is locked)
This will not modify the file or its metadata at all, even when it isn't locked.
Example usage
I use this method in my custom git mergetool script for merging Excel files. The way a git mergetool works is that it waits for the script shell to exit, then checks if the target file was modified, prompting with "XX.yyy seems unchanged. Was the merge successful [y/n]?" if it wasn't. However, Excel (at least the version I'm using) does not spawn a new process for each file it opens. So if Excel is already open, the script will exit immediately, and git will detect no changes to the file, resulting in that prompt.
So I devised the method above, and I use it like below:
REM block until MERGED is closed
:loop
powershell -Command "$FileStream = [System.IO.File]::Open('%MERGED%', 'Open', 'Write'); $FileStream.Close(); $FileStream.Dispose()" >NUL 2>NUL || (goto :loop)
Incidentally, dbenham's solution also seems to be an effective way to find out if a process is running. It was the best solution I found for the following application:
start /b "job1.exe >> job1.out"
start /b /wait "job2.exe >> job2.out"
::wait for job1 to finish using dbenham's code to check if job1.out is in use
comparejobs.exe
Just i want to share with you an example of my script based on #dbenham's trick
Description of this script : Check_Locked_Files.bat :
This script can scan and check for locked files on a set of folders that can be modified into the script; for example, i have chosen those set of folders to be scanned :
Set Folders=^
^ "%ProgramData%\Microsoft\Windows\Start Menu\Programs\Startup"^
^ "%UserProfile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"^
^ "%ProgramFiles%\Internet Explorer"^
^ "%ProgramFiles%\Skype"^
^ "%ProgramFiles%\TeamViewer"^
^ "%WinDir%\system32\drivers"^
^ "%Temp%"
The output result is in HTML format for more readability.
If the file is locked we show it in red color otherwise we show it in green color.
And the whole script is : Check_Locked_Files.bat
#echo off
Rem This source is inspired from here
Rem hxxps://stackoverflow.com/questions/
Rem 10518151/how-to-check-in-command-line-if-a-given-file-or-directory-is-locked-used-by-any?answertab=active#tab-top
Rem Thanks for dbenham for this nice trick ;)
Mode con cols=90 lines=5 & color 9E
Title Scan and Check for Locked Files by Hackoo 2017
set "LogFile=%~dp0%~n0.html"
(
echo ^<html^>
echo ^<title^> Scan and Check for locked files by Hackoo 2017^</title^>
echo ^<body bgcolor^=#ffdfb7^>
echo ^<center^>^<b^>Log Started on %Date% # %Time% by the user : "%username%" on the computer : "%ComputerName%"^</b^>^</center^>
)> "%LogFile%"
echo(
echo --------------------------------------------------------------------------
echo Please Wait a while ....... Scanning for locked files is in progress
echo --------------------------------------------------------------------------
Rem We Play radio just for fun and in order to let the user be patient until the scan ended
Call :Play_DJ_Buzz_Radio
Timeout /T 3 /nobreak>nul
cls
Set Folders=^
^ "%ProgramData%\Microsoft\Windows\Start Menu\Programs\Startup"^
^ "%UserProfile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"^
^ "%ProgramFiles%\Internet Explorer"^
^ "%ProgramFiles%\Skype"^
^ "%ProgramFiles%\TeamViewer"^
^ "%WinDir%\system32\drivers"^
^ "%Temp%"
#For %%a in (%Folders%) Do (
( echo ^<hr^>^<font color^=DarkOrange^>^<B^>Folder : %%a^</B^>^</font^>^<hr^>) >> "%LogFile%"
#for /f "delims=" %%b in ('Dir /A-D /s /b "%%~a\*.*"') do (
Call :Scanning "%%~nxb"
Call:Check_Locked_File "%%~b" "%LogFile%"
)
)
(
echo ^<hr^>
echo ^<center^>^<b^>Log ended on %Date% # %Time% on the computer : "%ComputerName%"^</b^>^</center^>
echo ^</body^>
echo ^</html^>
)>> "%LogFile%"
Start "" "%LogFile%" & Call :Stop_Radio & exit
::***********************************************************************************
:Check_Locked_File <File> <LogFile>
(
2>nul (
>>%1 (call )
) && ( #echo ^<font color^=green^>file "%~1"^</font^>^<br^>
) || (
#echo ^<font color^=red^>file "%~1" is locked and is in use^</font^>^<br^>
)
)>>%2 2>nul
exit /b
::***********************************************************************************
:Scanning <file>
cls
echo(
echo --------------------------------------------------------------------------
echo Please Wait a while... Scanning for %1
echo --------------------------------------------------------------------------
exit /b
::***********************************************************************************
:Play_DJ_Buzz_Radio
Taskkill /IM "wscript.exe" /F >nul 2>&1
Set "vbsfile=%temp%\DJBuzzRadio.vbs"
Set "URL=http://www.chocradios.ch/djbuzzradio_windows.mp3.asx"
Call:Play "%URL%" "%vbsfile%"
Start "" "%vbsfile%"
Exit /b
::**************************************************************
:Play
(
echo Play "%~1"
echo Sub Play(URL^)
echo Dim Sound
echo Set Sound = CreateObject("WMPlayer.OCX"^)
echo Sound.URL = URL
echo Sound.settings.volume = 100
echo Sound.Controls.play
echo do while Sound.currentmedia.duration = 0
echo wscript.sleep 100
echo loop
echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000
echo End Sub
)>%~2
exit /b
::**************************************************************
:Stop_Radio
Taskkill /IM "wscript.exe" /F >nul 2>&1
If Exist "%vbsfile%" Del "%vbsfile%"
::**************************************************************
:: Create the file Running.tmp
ECHO %DATE% > Running.tmp
ECHO %TIME% >> Running.tmp
:: block it and do the work
(
>&2 CALL :Work 30
) >> Running.tmp
:: when the work is finished, delete the file
DEL Running.tmp
GOTO EOF
:: put here the work to be done by the batch file
:Work
ping 127.0.0.1 -n 2 -w 1000 > NUL
ping 127.0.0.1 -n %1 -w 1000 > NUL
:: when the process finishes, the execution go back
:: to the line after the CALL
In case you want to use this in a Cygwin Bash, here are the one-liners:
# To lock a file: (in a different window)
cmd.exe /C "( >&2 pause ) >> test.txt"
#Press any key to continue . . .
# To test if a file is locked (with text)
cmd.exe /C "2>nul ( >>test.txt (call ) ) && (echo ok) || (echo locked)"
#locked
# To test if a file is locked (with POSIX exit code)
cmd.exe /C "2>nul ( >>test.txt (call ) ) && (exit /b 0) || (exit /b 1)"
echo $?
#1
In case of windows network share you can try powershell command:
Get-SmbOpenFile
For example execute on file server command as administrator:
Get-SmbOpenFile | Where-Object -Property Path -match "file.txt"