Batch Scripting - Saving the output of systeminfo command to a variable

2.4k Views Asked by At

I'm having a hard time trying to save the output of the following command, which gets me the name of the OS to a variable.

systeminfo | findstr /B /C:"OS Name" 

I tried using a for loop as shown below but then the value of the variable is OS

for /f %%i in ('systeminfo ^| findstr /B /C:"OS Name" ') do set vard=%%i
echo the operating system name 2 is %vard%

Can someone please help me out with this ? I took a look at other approaches such as writing the output to a temporary file and then reading it back later on but I'd like to achieve this without resorting to using temporary files

2

There are 2 best solutions below

0
michael_heath On
@echo off
setlocal

set "vard="

for /f "tokens=1,2,* delims=: " %%i in ('systeminfo') do (
    if "%%~i %%~j" == "OS Name" (
        call :clean_spaces "%%~k"
        goto :next
    )
)

:next
echo the operating system name 2 is "%vard%"
exit /b

:clean_spaces
setlocal enabledelayedexpansion
set "string=%~1"
    :loop
    if "!string:~-1!" == " " (
        set "string=!string:~,-1!"
        goto :loop
    )
endlocal & set "vard=%string%"

Delimit by colon and space. Unfortunately, token * also gets the trailing spaces which systeminfo outputs.

A label named :trim_spaces trims the trailing spaces from the value that vard stores. It does this by checking the last character if a space and removes it. It keeps looping until no trailing spaces exist.

0
Compo On

To use the slow SystemInfo method, as used in your posted code, you should delimit the output using the known separator character, :.

@Echo Off
For /F "Tokens=1* Delims=:" %%A In ('SystemInfo^|Find /I "OS Name"'
) Do Call :Sub %%B
Echo the operating system name 2 is %vard%
Pause
GoTo :EOF

:Sub
Set "vard=%*"
Exit /B

Alternatively, you can either use the built-in WMI command line, WMIC.exe.

@Echo Off
For /F "Skip=1 Delims=|" %%A In ('WMIC OS Get Name'
) Do For /F "Delims=" %%B In ("%%A") Do Call :Sub %%A
Echo the operating system name 2 is %vard%
Pause
GoTo :EOF

:Sub
Set "vard=%*"
Exit /B

Or retrieve the information from the registry, using Reg.exe:

@Echo Off
For /F "Skip=2 Tokens=2*" %%A In (
    'Reg Query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /V ProductName'
) Do Set "vard=%%B" 
Echo the operating system name 2 is %vard%
Pause
GoTo :EOF