Downloading jdk using powershell Downloading jdk using powershell powershell powershell

Downloading jdk using powershell


On inspecting the session on oracle site the following cookie catches attention: oraclelicense=accept-securebackup-cookie. With that in mind you can run the following code:

$source = "http://download.oracle.com/otn-pub/java/jdk/8u5-b13/jdk-8u5-windows-i586.exe"$destination = "C:\Download\Java\jdk-7u60-windows-i586.exe"$client = new-object System.Net.WebClient $cookie = "oraclelicense=accept-securebackup-cookie"$client.Headers.Add([System.Net.HttpRequestHeader]::Cookie, $cookie) $client.downloadFile($source, $destination)


EDIT: here's the reason for your problem: you can't directly download the file without accepting the terms before.

I'm using the following script to download files. It's working with HTTP as well as with FTP. It might be a little overkill for your task because it also shows the download progress but you can trim it untill it fits your needs.

param(    [Parameter(Mandatory=$true)]    [String] $url,    [Parameter(Mandatory=$false)]    [String] $localFile = (Join-Path $pwd.Path $url.SubString($url.LastIndexOf('/'))) )begin {    $client = New-Object System.Net.WebClient    $Global:downloadComplete = $false    $eventDataComplete = Register-ObjectEvent $client DownloadFileCompleted `        -SourceIdentifier WebClient.DownloadFileComplete `        -Action {$Global:downloadComplete = $true}    $eventDataProgress = Register-ObjectEvent $client DownloadProgressChanged `        -SourceIdentifier WebClient.DownloadProgressChanged `        -Action { $Global:DPCEventArgs = $EventArgs }    }process {    Write-Progress -Activity 'Downloading file' -Status $url    $client.DownloadFileAsync($url, $localFile)    while (!($Global:downloadComplete)) {                        $pc = $Global:DPCEventArgs.ProgressPercentage        if ($pc -ne $null) {            Write-Progress -Activity 'Downloading file' -Status $url -PercentComplete $pc        }    }    Write-Progress -Activity 'Downloading file' -Status $url -Complete}end {    Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged    Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete    $client.Dispose()    $Global:downloadComplete = $null    $Global:DPCEventArgs = $null    Remove-Variable client    Remove-Variable eventDataComplete    Remove-Variable eventDataProgress    [GC]::Collect()    }


After needing this script for a platform installer that required the JDK as a dependency:

<# Config #>$DownloadPageUri = 'https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html';$JavaVersion = '8u201';<# Build the WebSession containing the proper cookie    needed to auto-accept the license agreement. #>$Cookie=New-Object -TypeName System.Net.Cookie; $Cookie.Domain='oracle.com';$Cookie.Name='oraclelicense';$Cookie.Value='accept-securebackup-cookie'; $Session= `   New-Object -TypeName Microsoft.PowerShell.Commands.WebRequestSession;$Session.Cookies.Add($Cookie);<# Fetch the proper Uri and filename from the webpage. #>$JdkUri = (Invoke-WebRequest -Uri $DownloadPageUri -WebSession $Session -UseBasicParsing).RawContent `    -split "`n" | ForEach-Object { `        If ($_ -imatch '"filepath":"(https://[^"]+)"' { `            $Matches[1] `        } `    } | Where-Object { `        $_ -like "*-$JavaVersion-windows-x64.exe" `    }[0];If ($JdkUri -imatch '/([^/]+)$') {     $JdkFileName=$Matches[1];}<# Use a try/catch to catch the 302 moved temporarily    exception generated by oracle from the absance of   AuthParam in the original URL, piping the exception's   AbsoluteUri to a new request with AuthParam returned   from Oracle's servers.  (NEW!) #>try {     Invoke-WebRequest -Uri $JdkUri -WebSession $Session -OutFile "$JdkFileName"} catch {     $authparam_uri = $_.Exception.Response.Headers.Location.AbsoluteUri;    Invoke-WebRequest -Uri $authparam_uri -WebSession $Session -OutFile "$JdkFileName"} 

Works in PowerShell 6.0 (Hello 2019!) Required a minor fixup to the regex and the way the -imatch line scan happened. Workaround to follow 302 redirects was located here: https://github.com/PowerShell/PowerShell/issues/2896 (302 redirect workaround by fcabralpacheco readapted to get Oracle downloads working again !

This solution downloads 8u201 for Windows x64 automatically.