Link to home
Start Free TrialLog in
Avatar of michael4606
michael4606

asked on

Set DOS Variable to Command Output

Hello,

In a Windows DOS Console batch file I need to set the output of a command to a variable.  This is what technique I use now:

time /t > %TMP%\time.txt
set /p TIME1="" < %TMP%\time.txt

I use the time command as an example as I need to do this with similar commands that have small outputs.  The main goal is to be able to set the variable value to the output of a command WITHOUT having to dump it to a file first as shown above.

For example. in a UNIX Bourne shell script I would do it like this: MYVAR=`mycommand`

What can you recommend?


Thanks,

Michael4606
Avatar of Steve Knight
Steve Knight
Flag of United Kingdom of Great Britain and Northern Ireland image

Well you could probably do it with a pipe but that doesn't appear to work:

time /t|set /p test=""

But you can do it using a for command:

for /f "tokens=*" %a in ('time  /t') do set test=%a

or from a batch file us %%a instead.

You can do much more with for and set (have a look at set /? and for /?) to parse the output of the command etc. if needed too.

Steve

ASKER CERTIFIED SOLUTION
Avatar of Steve Knight
Steve Knight
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
or, in the case of time and date, just use the system variable already available:

@echo time: %time% , date: %date%
Well yes,  of course, but I was assuming that this was relating to the output of other application as was suggested, otherwise bit of a sledgehammer / nut situation :-)

You can also do it one line with

yourapp.exe > %temp%\x.txt & set /p test="" <%temp%\x.txt
Avatar of michael4606
michael4606

ASKER

Thanks sir - that was the ticket.
No problem

Steve