Last active
February 22, 2020 22:35
-
-
Save mkropat/16c5cf675faf29140e76ca72f0b4c0cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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