Skip to content

Instantly share code, notes, and snippets.

@Meir017
Last active November 17, 2023 11:20
Show Gist options
  • Save Meir017/b639e6cce3ff580cf6728220782c70b4 to your computer and use it in GitHub Desktop.
Save Meir017/b639e6cce3ff580cf6728220782c70b4 to your computer and use it in GitHub Desktop.
Download Docker Image powershell
param(
[Parameter(Mandatory = $true)]
[string]$ImageName,
[string]$Tag = 'latest',
[ValidateSet(
'DockerIO',
'Microsoft'
)]
[string]$Registry = 'DockerIO'
)
switch ($Registry) {
'DockerIO' {
$LocalImageName = $ImageName
if (! $ImageName.Contains('/')) {
$LocalImageName = "library/$ImageName"
}
$Response = Invoke-RestMethod "https://auth.docker.io/token?service=registry.docker.io&scope=repository:$($LocalImageName):pull"
$Headers = @{
Authorization = "Bearer $($Response.token)";
Accept = 'application/vnd.docker.distribution.manifest.v2+json';
}
}
Default {
$Headers = @{ }
}
}
switch ($Registry) {
'DockerIO' {
$LocalImageName = $ImageName
if (! $ImageName.Contains('/')) {
$LocalImageName = "library/$ImageName"
}
$DownloadMetadata = "https://registry-1.docker.io/v2/$LocalImageName/manifests/$Tag"
$DownloadLayer = "https://registry-1.docker.io/v2/$LocalImageName/blobs/"
}
'Microsoft' {
$DownloadMetadata = "https://mcr.microsoft.com/v2/$ImageName/manifests/$Tag"
$DownloadLayer = "https://mcr.microsoft.com/v2/$ImageName/blobs/"
}
}
Write-Host "Downloading url($DownloadMetadata) $($ImageName):$Tag from $Registry" -ForegroundColor DarkGray
$Response = Invoke-RestMethod $DownloadMetadata -Headers $Headers
$Layers = $Response.layers;
if (! $Layers) {
$Layers = $Response.manifests
}
if (! $Layers) {
$Layers = $Response.fsLayers
}
foreach ($Layer in $Layers) {
$LayerDigest = $Layer.digest ?? $Layer.blobSum
$LayerUrl = $DownloadLayer + $LayerDigest
$NormalizedName = $ImageName.Replace('/','_') + '__' + $LayerDigest.Replace(':', '_') + '.tar.gz'
Write-Host "Downloading $LayerDigest from $LayerUrl" -ForegroundColor DarkGray
Invoke-WebRequest $LayerUrl -Headers $Headers -OutFile $NormalizedName
Write-Host "Downloaded $LayerDigest"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment