Mikoyan
Mikoyan

Reputation: 59

Please explain usage for for/f command?

I am using the following to output the java version which I grabbed from another site:

java -version 2> java.txt
for /f "tokens=3" %%x in ('find /i "java version" java.txt') 

Output is:

java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)

Here is the full code:

@echo off

set JavaTemp=C:\Windows\Gpologs

java -version
if "%ErrorLevel%"=="0" ( goto VersionCheck ) ELSE ( goto Install )

:VersionCheck
java -version 2> %JavaTemp%\java.txt
for /f "tokens=3" %%x in ('find /i "java version" %JavaTemp%\java.txt') do (
  if %%~x==1.7.0_45 goto :eof
  if %%~x==1.7.0_40 goto Install
  if %%~x==1.7.0_25 goto Install
  if %%~x==1.7.0_21 goto Install
  if %%~x==1.7.0_17 goto Install
  if %%~x==1.7.0_15 goto Install
)

:Install
msiexec /i "\\servershare\sharename\Java\jre1.7.0_45_x86\jre1.7.0_45.msi" /qn
if %ErrorLevel% EQU 0 (
    >>"\\servershare\sharename\jre_1.7.45.x64.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Java Runtime 1.7.0_45x86 Installed"
    >>"%windir%\GpoLogs\jre_1.7.45.x64.txt" echo "Java Runtime 1.7.0_45x86 Installed"
) else (
    >>"\\servershare\sharename\JavaInstallErrors.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Error trying to install Java 1.7_45x86"
)

I just need to know why the tokens is 3? please explain as soon as I get my head around it, it will make a lot more sense :)

Upvotes: 1

Views: 245

Answers (2)

dbenham
dbenham

Reputation: 130889

Foxidrive answered your question.

Unrelated to your question, your code can be greatly simplified with the exact same result:

@echo off
for /f "tokens=3" %%V in (
  'java -version 2^>^&1 ^| find /i "java version"'
) do if %%~V==1.7.0_45 exit /b
msiexec /i "\\servershare\sharename\Java\jre1.7.0_45_x86\jre1.7.0_45.msi" /qn
if %ErrorLevel% EQU 0 (
  >>"\\servershare\sharename\jre_1.7.45.x64.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Java Runtime 1.7.0_45x86 Installed"
  >>"%windir%\GpoLogs\jre_1.7.45.x64.txt" echo "Java Runtime 1.7.0_45x86 Installed"
) else (
  >>"\\servershare\sharename\JavaInstallErrors.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Error trying to install Java 1.7_45x86"
)

Upvotes: 1

foxidrive
foxidrive

Reputation: 41242

The default delimiters are space and TAB

You count the 'words' in the string and use spaces/tabs as separators, and your 3rd token/word is "1.7.0_25"

Upvotes: 3

Related Questions