[Batch file] - Output of a command to variable

If you want to set the output of a command to a value you have to capture it in a for statement like this:
for /f "tokens=2 delims=:" %%a in ('systeminfo ^| find "OS Name"') do set OS_Name=%%a
Then remove the leading spaces like this: (there is probably a better way to do this)
for /f "tokens=* delims= " %%a in ("%OS_Name%") do set OS_Name=%%a
A few things to note here:
1.) "tokens=2 delims=:" is setting the delimiter to : and it is selecting the second section only, which will pull only the part you want. 
2.) the | is escaped with a ^, this needs to be done in for loops or anything after that will attempt to execute as seperate commands. 
3.) "tokens=* delims= " The token here is * which is all tokens.
=======================
Examples of WMIC output to variables:

echo WMIC output to variables
for /f "usebackq tokens=1,2 delims==|" %%I in (`wmic os get name^,version /format:list`) do 2>NUL set "%%I=%%J"
for /f "tokens=2 delims==" %%I in ('wmic bios get version /format:list') do set "bios=%%I"
for /f "tokens=2 delims==" %%I in ('wmic computersystem get model /format:list') do set "model=%%I"
echo OS Name: %name%
echo OS Version: %version%
echo PC Model: %model%
echo BIOS Version: %bios%
echo:
pause

Another way:
FOR /F "TOKENS=1,* DELIMS==" %%u IN ('WMIC OS GET CAPTION /VALUE') DO IF /I "%%u"=="Caption" SET vers=%%v 


FOR /F "usebackq delims=: tokens=2" %%i IN (osname.txt) DO set vers=%%i
FOR /F "usebackq delims=  tokens=2" %%i IN (osname.txt) DO set vers=%%i
Another:
for /f "tokens=2 delims==" %%I in ('wmic computersystem get model /format:list') do set "SYSMODEL=%%I"
set "Line1=*** System Model: %SYSMODEL%"
echo %Line1%

Comments

Popular posts from this blog

vRA/vRO workflows

How to generate HPS Report for Windows