I'm trying to set the output of a commandline program to a variable in a Windows batch file. For example, if I'd like to read the output of the "ver" command (which tells you what version of window) to a variable called "myvar", how would I do it?
So "ver" outputs for me:
"Microsoft Windows XP [Version 5.1.2600]"
How would I read that into a variable called myvar?
I tried piping it, but can't figure out what the syntax would be.
This is trivial in other languages such as PHP, where I'd simply have:
Here is another example I wrote using FOR statements that will not require you to output anything to a text file first. This is important if you are working in areas where you might not have write access. I also noticed that you sometimes need to remove spaces like from the Date /T or Ver commands which return something like "Tue 06/20/2009" or "Microsoft Windows Version [6.0.6001]" into separate variables.
@ECHO OFF
:; Clear the screen and turn echo off (above) to keep it clean
CLS
:; Clear any previous variables set
SET Today=
SET DayMonth=
SET MonthDay=
SET Year=
SET Var1=
SET WinVer=
SET WinMajor=
SET WinMinor=
SET WinBuild=
SET WeekDay=
SET DayOfWeek=
:; Get Value from 'VER' command output
FOR /F "tokens=*" %%i in ('VER') do SET WinVer=%%i
FOR /F "tokens=1-3 delims=]-" %%A IN ("%WinVer%" ) DO (
SET Var1=%%A
)
:; Get version number only so drop off Microsoft Windows Version
FOR /F "tokens=1-9 delims=n" %%A IN ("%Var1%" ) DO (
SET WinVer=%%C
echo %WinVer%
)
:; Separate version numbers
FOR /F "tokens=1-8 delims=.-" %%A IN ("%WinVer%" ) DO (
SET WinMajor=%%A
SET WinMinor=%%B
SET WinBuild=%%C
)
:; Fix the extra space left over in the Major
FOR /F "tokens=1 delims= " %%A IN ("%WinMajor%" ) DO (
SET WinMajor=%%A
)
:; Get the output from the "Date /T"
FOR /F "tokens=*" %%i in ('DATE /T') do SET Today=%%i
FOR /F "tokens=1-3 delims=/-" %%A IN ("%Today%" ) DO (
SET DayMonth=%%A
SET MonthDay=%%B
SET Year=%%C
)
:; Separate the Day from Month like "Tue 06" to "Tue"
FOR /F "tokens=1 delims= " %%A IN ("%DayMonth%" ) DO (
SET DayOfWeek=%%A
)
:; Separate the Day from Month like "Tue 06" to "06"
FOR /F "tokens=2 delims= " %%A IN ("%DayMonth%" ) DO (
SET Month=%%A
)
:; Now show the date output using your variables
ECHO Month = %Month%
ECHO DayOfWeek = %DayOfWeek%
ECHO Date = %DayOfWeek% %Month%/%MonthDay%/%Year%
Yes that's correct! I used ver which will display the windows version with something like "Microsoft Windows [Version 6.0.6001]" but you can use any command line application.