Ubuntu.ps1
# https://www.lucd.info/2019/12/06/cloud-init-part-1-the-basics/ # https://gist.github.com/leogallego/a614c61457ed22cb1d960b32de4a1b01 function Get-OVF { } function Get-Ubuntu { param ( [string] $Path, [string] $File, [bool] $Update ) $cacheDir = Get-BoxPath -Path "cache" $imageFile = Join-Path $cacheDir $File # If not update and image file exists we have it if (-Not($Update)) { if (Test-Path $imageFile -PathType Leaf) { return $imageFile } } $ProgressPreference = "SilentlyContinue" $url = (("https://cloud-images.ubuntu.com", $Path, $File) -join "/") Write-Verbose $url # If update and we have a file, check if there's one newer if (Test-Path $imageFile -PathType Leaf) { Write-Host "Checking new image '$File' ..." -NoNewline $response = Invoke-WebRequest $url -UseBasicParsing -Method Head Write-Host -ForegroundColor Green " Done." $lastModified = Get-Date -Date ($response.Headers["Last-Modified"]) $fileTime = (Get-ChildItem $imageFile | Select-Object CreationTime).CreationTime if ($fileTime -gt $lastModified) { return $imageFile } } # Download file Write-Host "Checking new image size '$File' ..." -NoNewline $response = Invoke-WebRequest $url -UseBasicParsing -Method Head Write-Host -ForegroundColor Green " Done." $downloadSize = [int]$response.Headers["Content-Length"] $tmpFile = Join-Path $cacheDir "${File}.tmp" if (Test-Path $tmpFile -PathType Leaf) { Remove-Item $tmpFile } Write-Host "Downloading new image '$File' ($([int]($downloadSize / 1024 / 1024)) MB)..." -NoNewline Invoke-WebRequest $url -OutFile $tmpFile Write-Host -ForegroundColor Green " Done." # Check file hash $hashPath = (("https://cloud-images.ubuntu.com", $Path, "SHA256SUMS") -join "/") Write-Host "Checking file hash for '$File' ..." -NoNewline $hashSums = [System.Text.Encoding]::UTF8.GetString((Invoke-WebRequest $hashPath -UseBasicParsing).Content) $fileHash = Get-FileHash $tmpFile -Algorithm SHA256 if (($hashSums | Select-String -pattern $fileHash.Hash -SimpleMatch).Count -eq 0) { Remove-Item $tmpFile Write-Host -ForegroundColor Red "File hash check failed" exit } Write-Host -ForegroundColor Green " Done." $ProgressPreference = "Continue" # Replace file if (Test-Path $imageFile -PathType Leaf) { Remove-Item $imageFile } Move-Item $tmpFile $imageFile return $imageFile } |