Artifacts/windows-download-sas-blob/artifact.ps1 (72 lines of code) (raw):

[CmdletBinding()] param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)] [string] $Uri, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)] [string] $Path, [int] $TimeoutSec = 60 ) ################################################################################################### # # PowerShell configurations # # NOTE: Because the $ErrorActionPreference is "Stop", this script will stop on first failure. # This is necessary to ensure we capture errors inside the try-catch-finally block. $ErrorActionPreference = "Stop" # Ensure we force use of TLS 1.2 for all downloads. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Ensure we set the working directory to that of the script. pushd $PSScriptRoot ################################################################################################### # # Functions used in this script. # function Handle-LastError { [CmdletBinding()] param( ) $message = $error[0].Exception.Message if ($message) { Write-Host -Object "ERROR: $message" -ForegroundColor Red } # IMPORTANT NOTE: Throwing a terminating error (using $ErrorActionPreference = "Stop") still # returns exit code zero from the PowerShell script when using -File. The workaround is to # NOT use -File when calling this script and leverage the try-catch-finally block and return # a non-zero exit code from the catch block. exit -1 } ################################################################################################### # # Handle all errors in this script. # trap { # NOTE: This trap will handle all errors. There should be no need to use a catch below in this # script, unless you want to ignore a specific error. Handle-LastError } ################################################################################################### # # Main execution block. # try { # Ensure the path is available. if (-not [System.IO.Path]::IsPathRooted($Path)) { $Path = Join-Path $Env:Temp $Path } Write-Host "Ensuring local path $Path" New-Item -ItemType Directory -Force -Path (Split-Path -parent $Path) | Out-Null # Download requested file. Write-Host "Downloading file from $Uri" Invoke-WebRequest -Uri $Uri -OutFile $Path -TimeoutSec $TimeoutSec } finally { popd }