Monday, August 13, 2007

Assigning an programs output to a variable in a batch file

This one took me longer than it should have to figure out. I had to write a batch file to integrate with our monitoring appliance - I can't really remember the last time I had to do this, but the number 6.22 comes to mind.

Anyways, the goal was to set a variable's value to the output (note: note the exit code) to the variable. You can't do this with the SET command so I had to result to using the FOR statement.

From a command prompt, it looks like:

for /f "tokens=*" %a in ('Program.exe "argument1"') do set __VARIABLENAME__=%a

Only one gotcha - in a batch file, you need to double up your % identifiers.

REM This is the start of the batch file
for /f "tokens=*" %%a in ('Program.exe "argument1"') do set __VARIABLENAME__=%%a
echo Result is %__VARIABLENAME__%
REM This is the end of the batch file

I'm glad thats over, back to C# for me!

No comments: