Public/Tasks/Invoke-EnsureJavaInstalledTask.ps1

#Requires -Modules SitecoreInstallFramework, SitecoreFundamentals

Set-StrictMode -Version Latest

Write-Verbose "Loading $($MyInvocation.MyCommand.Path)"

Function Invoke-EnsureJavaInstalledTask {
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param(
        [string]$JreDownloadUrl = "http://download.oracle.com/otn-pub/java/jdk/8u152-b16/aa0333dd3019491ca4f6ddbe78cdb6d0/jre-8u152-windows-x64.exe",
        [string]$TaskName = "EnsureJavaInstalled"
    )

    Set-PSDebug -Strict

    $TempFolder = "$env:TEMP"
    $downloadFolder = "$TempFolder\java"
    $jrehk = Test-Path "HKLM:\SOFTWARE\JavaSoft\Java Runtime Environment"
    $jreinstalled = $false
    if ($jrehk) {

        $jreversion = (Get-ItemProperty -Path "HKLM:\SOFTWARE\JavaSoft\Java Runtime Environment" -Name CurrentVersion).CurrentVersion
        $jrehome = (Get-ItemProperty -Path "HKLM:\SOFTWARE\JavaSoft\Java Runtime Environment\$jreversion" -Name JavaHome).JavaHome
        $jreinstalled = Test-Path $jrehome
    }

    # is java installed?
    if (-not ($jreinstalled)) {
        # download installer
        $jreexe = Split-Path $JreDownloadUrl -Leaf

        if ($PSCmdlet.ShouldProcess($JreDownloadUrl)) {

            Invoke-EnsurePathTask -Exists $downloadFolder

            $jredlexe = "$downloadFolder\$jreexe"
            $client = new-object System.Net.WebClient
            $cookie = "oraclelicense=accept-securebackup-cookie"
            $client.Headers.Add([System.Net.HttpRequestHeader]::Cookie, $cookie)
            $client.downloadFile($JreDownloadUrl, $jredlexe)

            # execute installer
            Invoke-CommandTask $jredlexe -Arguments '/s', 'INSTALL_SILENT=1', 'STATIC=0', 'AUTO_UPDATE=0', 'WEB_JAVA=1', 'WEB_JAVA_SECURITY_LEVEL=H', 'WEB_ANALYTICS=0', 'EULA=0', 'REBOOT=0', 'NOSTARTMENU=0', 'SPONSORS=0' -TaskName "EnsureJava"

            Write-TaskInfo "Insalled Java" -Tag Java -TaskName $TaskName

            Invoke-EnsurePathTask -Clean $downloadFolder -Verbose
        }
    }
    else {
        Write-TaskInfo "Java already installed." -Tag Java -TaskName $TaskName
    }

}

Register-SitecoreInstallExtension -Command Invoke-EnsureJavaInstalledTask -As EnsureJavaInstalled -Type Task -Force -Verbose

Write-Verbose "Loaded $($MyInvocation.MyCommand.Path)"