Batch Script – Reading parameter file into variables

Hi folks, quick tip on how to easily read a parameter file from a batch script. This is an idea I had to make the life easier when trying to troubleshoot connection issues from client to server and I had to change a lot the service names, server names, user and passwords and so on.

In the example I will have the parameter file (parameter.ini) and the script (testConn.bat)

parameter.ini:

############################################
# Parameter file for testConn.bat
############################################
# Adjust the parameters according to your
# needs.
# Important: Do not leave spaces after "="
############################################
USERNAME       =SCOTT
PASSWORD       =TIGER
SERVER         =example.localdomain
PORT           =1521
SERVICE_NAME   =ORCL
TNSALIAS       =ORCL

testConn.bat:

@ECHO OFF
CLS
:readParameters
FOR /F "tokens=* USEBACKQ" %%F IN (`FINDSTR /C:"USERNAME" "%CD%"\parameters.ini`) DO (SET USERNAME=%%F)
FOR /F "tokens=* USEBACKQ" %%F IN (`FINDSTR /C:"PASSWORD" "%CD%"\parameters.ini`) DO (SET PASSWORD=%%F)
FOR /F "tokens=* USEBACKQ" %%F IN (`FINDSTR /C:"SERVER" "%CD%"\parameters.ini`) DO (SET SERVER=%%F)
FOR /F "tokens=* USEBACKQ" %%F IN (`FINDSTR /C:"PORT" "%CD%"\parameters.ini`) DO (SET PORT=%%F)
FOR /F "tokens=* USEBACKQ" %%F IN (`FINDSTR /C:"SERVICE_NAME" "%CD%"\parameters.ini`) DO (SET SERVICE_NAME=%%F)
FOR /F "tokens=* USEBACKQ" %%F IN (`FINDSTR /C:"TNSALIAS" "%CD%"\parameters.ini`) DO (SET TNSALIAS=%%F)
SET USERNAME=%USERNAME:~16%
SET PASSWORD=%PASSWORD:~16%
SET SERVER=%SERVER:~16%
SET PORT=%PORT:~16%
SET SERVICE_NAME=%SERVICE_NAME:~16%
SET TNSALIAS=%TNSALIAS:~16%

:tnsnames
sqlplus %USERNAME%/%PASSWORD%@%TNSALIAS%

:ezconnect
sqlplus %USERNAME%/%PASSWORD%@//%SERVER%:%PORT%/%SERVICE_NAME%

exit

As you may have noticed, the big trick here is to simply read starting at a desired position (16 in my case) and use the findstr command to filter the strings and get precisely what is wanted into each variable.

Advertisements

About Bruno Carvalho

Coffee addicted tech guy.
This entry was posted in Scripts and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s