Wednesday 1 July 2015

Getting Java INSTALLDIR through VBScript and using this value to assign to a system environment variable - Advance Application Packaging


During packaging there is case where SYSTEM Environment variable needs to be created and it value supposed to be a path of JAVA installed, and this path will deffer from defferent verion to version of java.

Firstly it is difficult to find java path installed on system using MSI System search, so this is the alternative way to get this path.

Drawback of this script if there are two java installed on same system it will return first path found, to overcome this issue we can specify search string more clearly  in pattern matching string. In my example it it "jre" only

I have created a SYSTEM environment variable named "JRE64_HOME"
and its value supposed to be "C:\Program Files\Java\jre1.8.0_45" which is fetch by script.
This value will defer from system to system.


Option Explicit
On Error Resume Next
Dim objshell, objFSO, StrprgData, objFolder, colSubfolders, objRegEx, colMatches
Dim Path, Test, objSubfolder
Dim strVarName, objVar, objVarClass

Set objShell=CreateObject ("wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
StrprgData = objShell.ExpandEnvironmentStrings("%ProgramFiles%")

'This is the folder location "C:\Program Files\Java"
'script will look for subfolder of this folder Foe Ex here : "jre1.8.0_45"

Set objFolder = objFSO.GetFolder( StrprgData & "\java")
Set colSubfolders = objFolder.Subfolders

Set objVarClass = GetObject( "winmgmts://./root/cimv2:Win32_Environment" )
For Each objSubfolder in colSubfolders
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.Pattern = "jre"
'This ascript will check all subfolders of java and return first occourance of
'folder which name starts with "jre"

Set colMatches = objRegEx.Execute(objSubfolder.Name)
If colMatches.Count = 1 Then
Path = StrprgData & "\java\"

If objfso.FolderExists ( Path & objSubfolder.Name) Then
Test = StrprgData & "\java\" & objSubfolder.Name

'Test will return - C:\Program Files\Java\jre1.8.0_45
End If
End if
Next

'Below code will create a system variable JRE64_HOME and
'its value will be path returned by "Test" variable

strVarName = "JRE64_HOME"
Set objVar      = objVarClass.SpawnInstance_
objVar.Name          = strVarName
objVar.VariableValue = Test
objVar.UserName      = "<SYSTEM>"
objVar.Put_
'WScript.Echo "Created environment variable " & strVarName
Set objVar      = Nothing
Set objVarClass = Nothing



Thank you for reading :)
 

1 comment: