Sunday 5 July 2015

Working with Batch or Command Files



Using batch files as a deployment scripts
Batch files or Command [.cmd] files are still used for deployment purpose in many organizations.

Batch files are simple text files containing some lines with commands that get executed in sequence, one after the other. These files have the special extension BAT or CMD. Files of this type are recognized and executed through an interface (sometimes called a shell) provided by a system file called the command interpreter. 

These are using to trigger SQL Scripts, copy files etc ... This article explains how to create batch files for deployment purpose.

Creating a simple batch/cmd file:

Below file executes a SQL Script file from a specific path, this file accepts server and database as parameters:

@echo off
set /p sname= Please enter the servername:
set /p dbname= Please enter the databasename:
set /p pwd= Please enter the password:
sqlcmd -E -S %sname% -D %dbname% -P %PWD% -i "C:\location\your query.sql" -b)

With Error handling:

echo off
setlocal enabledelayedexpansion
set /p servername=Enter DB Servername :
set /p dbname=Enter Database Name :
set /p spath=Enter Script Path :
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
set logfilepath= %spath%\output_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.log
set cmd='dir %spath%\*.sql /b/s'
FOR /f %%G IN (%cmd%) DO (
echo ******PROCESSING %%G FILE******
echo ******PROCESSING %%G FILE****** >> %logfilepath%
SQLCMD -S%servername% -E -d%dbname% -b -i%%G >> %logfilepath%
IF !ERRORLEVEL! NEQ 0 GOTO :OnError
)
GOTO :Success

:OnError
echo ERROR ERROR ERROR
echo One\more script(s) failed to execute, terminating bath.
echo Check output.log file for more details
EXIT /b

:Success
echo ALL the scripts deployed successfully!!
EXIT /b





No comments:

Post a Comment