Reputation: 5
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"
Upvotes: 0
Views: 1485
Reputation: 200233
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
Upvotes: 0
Reputation: 3596
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'
Upvotes: 1