Setting Batch Variables Dynamically
One of the challenges of managing builds and deployments of source on multiple developer machines is that it can be complicated to contain and manage different variations in developer environments.
For example, often times, it is useful to know the server name or the connection string information so that local settings don’t make it into source control.
How I’ve often tackled this is to add a batch file that every developer executes when getting the source for the first time. This batch file asks for various settings and then saves the results to a text file which is then read back when executing other batch files.
Here is an example of such a 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 ECHO ================================================================ ECHO Creates the developer specific local configuration for builds ECHO that will allow developers to use local settings for specifc ECHO aspects of the deployment. ECHO ================================================================ :SPURL SET SPURL= SET /P SPURL=Enter SharePoint site URL (ex. http://mymachine:2345/): %=% IF "%SPURL%"=="" GOTO SPURL ECHO ---------------------------------------------------------------- :SQLCONN SET SQLCONN= ECHO Enter SQL connection string to the IC membership database ECHO (ex. Server=VM1;Database=IPDB;User ID=membershipUser;Password=P@ssw0rd;Application Name=HeCoreServices): SET /P SQLCONN= IF "%SQLCONN%"=="" GOTO SQLCONN ECHO ---------------------------------------------------------------- ECHO SPURL=%SPURL% > build-configuration.txt ECHO SQLCONN=%SQLCONN% >> build-configuration.txt ECHO Completed; created file build-configuration.txt PAUSE |
This batch file will prompt the developer for two settings: the URL of a site and the connection string that the developer is using locally (which can vary by the database name, login, etc.). The contents get written to a file called build-configuration.txt that looks like this:
1 2 |
SPURL=http://mymachine:2345 SQLCONN=Server=VM1;Database=IPDB;User ID=membershipUser;Password=P@ssw0rd;Application Name=HeCoreServices |
This file is excluded from source control and developers can, of course, manually edit this file as well to create local settings.
Now when I’m ready to use these settings in another batch file, I can invoke it like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION FOR /F "tokens=*" %%n IN (build-configuration.txt) DO ( ECHO %%n SET %%n ) ECHO %SPURL% ECHO %SQLCONN% PAUSE |
There are other ways to do this as well, but the downside to most approaches is that you have to know how many parameters you have or use less meaningful names. This approach will let you set variables to your heart’s content and read them in dynamically at execution.