Monday, August 26, 2013

Batch File - Output Command to Variable

I am by no means an expert in batch scripting and if you follow my posts you will have noticed I'm more of a VB scripting man.  However I was doing some batch scripting for a customer of mine today in which I need to export some data from a command line executable tool to a variable.

This can be done as follows:

FOR /F "delims=" %i IN ('date /t') DO set today=%i
echo %today%


Now one thing which caught me out,  if you put this code into a batch script "as is" you will notice the script will error out.  This is because to declare variables in a batch script you must use two % signs instead of one.

For example, "set today=%I" needs to be "set today=%%i".  To put the code in a batch script and to make it run you would use:

FOR /F "delims=" %%i IN ('date /t') DO set today=%%i
echo %today%

I hope this small post has been helpful - thankyou for reading.

No comments:

Post a Comment