Search code examples
windowsbatch-filecommand-linecommand-promptprompt

How to create a Condition in batch windows?


I have a script that I am trying to create a function to execute some commands according to the system version.

To know which version of Windows I do:

systeminfo | Findstr / B / C: "OS Name" / C: "OS Version"> version.txt
set version = <version.txt
del version.txt
echo% version% #(variable test, ok)

I need the following function (more or less like I would in Linux batch):

if [echo% version% | Findstr / B / C: "Windows XP"> "0"] {
echo "Windows XP"
}
if [echo% version% | Findstr / B / C: "Windows 7"> "0"] {
echo "Windows 7"
}
if [echo% version% | Findstr / B / C: "Windows 8"> "0"] {
echo "Windows 8"
}
if [echo% version% | Findstr / B / C: "Windows 10"> "0"] {
echo "Windows 10"
}

Solution

  • I prefer this method from VER command :

    @Echo off
    For /f "tokens=4,5,6 delims=[]. " %%G in ('ver') Do (set _major=%%G& set _minor=%%H& set _build=%%I) 
    
    Echo Major version: [%_major%]
    Echo Minor Version: [%_minor%]
    Echo Build: [%_build%]
    
    GOTO sub%_major%-%_minor%
    
    :sub6-0
    Echo Windows Vista or Windows 2008
    goto next
    
    :sub6-1
    Echo Windows 7 or Windows 2008 R2
    goto next
    
    :sub6-2
    Echo Windows 8 or Windows Server 2012
    goto next
    
    :sub6-3
    Echo Windows 8.1 or Windows Server 2012
    goto next
    
    :sub10-0
    :sub10-1
    Echo Windows 10 or Windows 2016
    
    :next
    Echo Architecture: [%PROCESSOR_ARCHITECTURE%]
    pause
    

    Or with this batch can did also the trick :

    @echo off
    setlocal
    for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
    if "%version%" == "5.1"     ( set "OS=Windows XP" )
    if "%version%" == "5.2"     ( set "OS=Windows XP Professional x64 Edition" )
    if "%version%" == "6.0"     ( set "OS=Windows Vista" )
    if "%version%" == "6.1"     ( set "OS=Windows 7" )
    if "%version%" == "6.2"     ( set "OS=Windows 8" )
    if "%version%" == "6.3"     ( set "OS=Windows 8.1" )
    if "%version%" == "10.0"    ( set "OS=Windows 10" )
    
    echo OS is "%OS%"
    echo The version is "%version%"
    endlocal
    pause