Skip to content

Instantly share code, notes, and snippets.

@mkropat
Last active February 22, 2020 22:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkropat/16c5cf675faf29140e76ca72f0b4c0cf to your computer and use it in GitHub Desktop.
Save mkropat/16c5cf675faf29140e76ca72f0b4c0cf to your computer and use it in GitHub Desktop.
function Get-WebFile {
param(
[Parameter(Mandatory=$true)]
$Uri,
[string] $OutFile,
[string] $Hash,
[string] $HashAlgorithm = 'SHA256'
)
if (-not $OutFile) {
$OutFile = Split-Path -Leaf $Uri
}
$meta = Get-Item $OutFile -ErrorAction SilentlyContinue
if ($meta -and $meta.PSIsContainer) {
throw '$OutFile may not be a directory'
}
$container = Split-Path $OutFile
if (-not $container) {
$container = '.'
}
$tempFile = Join-Path $container "$(New-Guid).part"
Invoke-WebRequest $Uri -OutFile $tempFile -ErrorAction Stop
if ($Hash) {
$actual = Get-FileHash $tempFile -Algorithm $HashAlgorithm
if ($Hash -ne $actual.Hash) {
throw "Downloaded file does not have the expected $HashAlgorithm hash: $Hash"
}
}
Move-Item $tempFile $OutFile -Force
Get-Item $OutFile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment