Skip to content

Instantly share code, notes, and snippets.

@jermdavis
Last active November 23, 2021 13:30
Show Gist options
  • Save jermdavis/6c527452dfa0c3c52b679b94caff9402 to your computer and use it in GitHub Desktop.
Save jermdavis/6c527452dfa0c3c52b679b94caff9402 to your computer and use it in GitHub Desktop.
Download files from dev.sitecore.net from the commandline - see https://blog.jermdavis.dev/posts/2017/downloading-stuff-from-dev-sitecore-net for info
param(
[Parameter(Mandatory=$true)]
[string]$url,
[Parameter(Mandatory=$true)]
[string]$target
)
function Fetch-WebsiteCredentials
{
$file = "dev.creds.xml"
if(Test-Path ".\\$file")
{
$cred = Import-Clixml ".\\$file"
}
else
{
$cred = Get-Credential -Message "Enter your SDN download credentials:"
$cred | Export-Clixml ".\\$file"
}
return $cred
}
function Fetch-DownloadAuthentication($cred)
{
$authUrl = "https://dev.sitecore.net/api/authorization"
$pwd = $cred.GetNetworkCredential().Password
$postParams = "{ ""username"":""$($cred.UserName)"", ""password"":""$pwd"" }"
$authResponse = Invoke-WebRequest -Uri $authUrl -Method Post -ContentType "application/json;charset=UTF-8" -Body $postParams -SessionVariable webSession
$authCookies = $webSession.Cookies.GetCookies("https://sitecore.net")
$marketPlaceCookie = $authCookies["marketplace_login"]
if([String]::IsNullOrWhiteSpace($marketPlaceCookie))
{
throw "Credentials appear invalid"
}
$devUrl = "https://dev.sitecore.net"
$devResponse = Invoke-WebRequest -Uri $devUrl -WebSession $webSession
$devCookies = $webSession.Cookies.GetCookies("https://dev.sitecore.net")
$sessionCookie = $devCookies["ASP.Net_SessionId"]
return "$marketPlaceCookie; $sessionCookie"
}
function Invoke-FileDownload
{
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string] $Uri,
[Parameter(Mandatory)]
[string] $OutputFile,
[string] $cookies
)
$webClient = New-Object System.Net.WebClient
if(!([String]::IsNullOrWhiteSpace($cookies)))
{
$webClient.Headers.Add([System.Net.HttpRequestHeader]::Cookie, $cookie)
}
$data = New-Object psobject -Property @{Uri = $Uri; OutputFile = $OutputFile}
$changed = Register-ObjectEvent -InputObject $webClient -EventName DownloadProgressChanged -MessageData $data -Action {
Write-Progress -Activity "Downloading $($event.MessageData.Uri)" -Status "To $($event.MessageData.OutputFile)" -PercentComplete $eventArgs.ProgressPercentage
}
try
{
$handle = $webClient.DownloadFileAsync($Uri, $PSCmdlet.GetUnresolvedProviderPathFromPSPath($OutputFile))
while ($webClient.IsBusy)
{
Start-Sleep -Milliseconds 10
}
}
finally
{
Write-Progress -Activity "Downloading $Uri" -Completed
Remove-Job $changed -Force
Get-EventSubscriber | Where SourceObject -eq $webClient | Unregister-Event -Force
}
}
$cred = Fetch-WebsiteCredentials
$cookie = Fetch-DownloadAuthentication $cred
Invoke-FileDownload -Uri $url -OutputFile $target -Cookies $cookie
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment