0

I have some issues with getting the java version out as a string. In a batch script I have done it like this:

for /f tokens^=2-5^ delims^=.-_^" %%j in ('%EXTRACTPATH%\Java\jdk_extract\bin\java -fullversion 2^>^&1') do set "JAVAVER=%%j.%%k.%%l_%%m"

The output is: 1.8.0_121

Now I want to do this for PowerShell, but my output is: 1.8.0_12, I miss one "1" in the end Now I have tried it with trim and split but nothing gives me the right output can someone help me out? This is what I've got so var with PowerShell

$javaVersion = (& $extractPath\Java\jdk_extract\bin\java.exe -fullversion 2>&1)
$javaVersion = "$javaVersion".Trim("java full version """).TrimEnd("-b13")

The full output is: java full version "1.8.0_121-b13"

2
  • Please edit the question and add the original version string that is to be parsed. Commented Dec 4, 2018 at 8:59
  • @vonPryz done ;) Commented Dec 4, 2018 at 9:12

2 Answers 2

1

TrimEnd() works a little different, than you might expect:

'1.8.0_191-b12'.TrimEnd('-b12') 

results in: 1.8.0_19 and so does:

'1.8.0_191-b12'.TrimEnd('1-b2')

The reason is, that TrimEnd() removes a trailing set of characters, not a substring. So .TrimEnd('-b12') means: remove all occurrences of any character of the set '-b12' from the end of the string. And that includes the last '1' before the '-'.

A better solution in your case would be -replace:

'java full version "1.8.0_191-b12"' -replace 'java full version "(.+)-b\d+"','$1'
Sign up to request clarification or add additional context in comments.

2 Comments

Can you maybe explain what the "(.+)-b\d+"','$1' code does? so i can use it in the future?
It is called a regular expression. For details on this particular pattern, see here: regex101.com/r/Z3UZqT/1 .
0

Use a regular expression for matching and extracting the version number:

$javaVersion = if (& java -fullversion 2>&1) -match '\d+\.\d+\.\d+_\d+') {
    $matches[0]
}

or

$javaVersion = (& java -fullversion 2>&1 | Select-String '\d+\.\d+\.\d+_\d+').Matches[0].Groups[0].Value

1 Comment

Thanks for your comment, this worked to ;) i have used the -replace for now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.