问题
I need to determine what's the highest installed version of LocalDB within a batch script and set the whole version string into a variable.
sqllocaldb versions
produces an out put like:
Microsoft SQL Server 2012 (11.0.5058.0) Microsoft SQL Server 2014 (12.0.2000.8)
The order of the version string is not necessarily ascending. Need some help to set the highest server version into a variable (in this example 12.0.2000.8).
回答1:
you need to invoke the command and parse the returned string, with a combination of FOR
command and SET
command,
for /f "tokens=5" %%a in ('sqllocaldb versions') do (
set verstr=%%a
set verstr=!verstr:^(=!
set verstr=!verstr:^)=!
then parse the version string into pieces with another FOR
command, and compute a version number with a SET /A
and simple arithmetic
for /f "tokens=1,2,3 delims=." %%b in ("!verstr!") do (
set /a verval=%%b*1000000+%%c*1000+%%d
then compare it with a running max using IF GTR
command
if !verval! gtr !highval! (
set /a highval=!verval!
set highest=!verstr!
)
so, putting all the pieces together....
@echo off
setlocal enabledelayedexpansion
set /a highval=0
for /f "tokens=5" %%a in ('sqllocaldb versions') do (
set verstr=%%a
set verstr=!verstr:^(=!
set verstr=!verstr:^)=!
for /f "tokens=1,2,3 delims=." %%b in ("!verstr!") do (
set /a verval=%%b*1000000+%%c*1000+%%d
if !verval! gtr !highval! (
set /a highval=!verval!
set highest=!verstr!
)
)
)
echo !highest!
回答2:
Edit improved: no auxiliary batch script required. Next code snippet could work (note proper escaping applied to inner loop):
@ECHO OFF
SETLOCAL enableextensions
echo show variables before
set _lastver
rem with an auxiliary batch script
>"%temp%\31110044.bat" ((for /f "tokens=1,2 delims=()" %%a in ('
sqllocaldb versions
') do @echo @set "_lastverCall=%%b")|sort)
call "%temp%\31110044.bat"
rem using two nested 'for /F' loops:
rem (note proper escaping applied to inner loop)
for /F "usebackq delims=" %%x in (`
^(for /f "tokens=1,2 delims=()" %%a in ^(^'
sqllocaldb versions
^'^) do @echo %%b^)^|sort
`) do set "_lastverForF=%%x"
echo show variables after
set _lastver
Output:
==>D:\bat\SO\31110044.bat
show variables before
Environment variable _lastver not defined
show variables after
_lastverCall=12.0.2000.8
_lastverForF=12.0.2000.8
==>
Debugged with fictional values in type "files\31110044.txt"
instead of sqllocaldb versions
:
==>type "files\31110044.txt"
MiniSoft SQL Server 2012 (11.0.5058.0)
MiniSoft SQL Server 2014 ( 2.0.2000.4)
MiniSoft SQL Server 2013 (11.0.5046.0)
MiniSoft SQL Server 2014 (12.0.2000.8)
MiniSoft SQL Server 2014 (11.0.4046.6)
==>
来源:https://stackoverflow.com/questions/31110044/batch-to-find-highest-version-string-from-amount-of-lines