Skip to content

Instantly share code, notes, and snippets.

@kimboslice99
Last active April 30, 2024 17:30
Show Gist options
  • Save kimboslice99/33b356e30b7504216d1b27a27fa8db26 to your computer and use it in GitHub Desktop.
Save kimboslice99/33b356e30b7504216d1b27a27fa8db26 to your computer and use it in GitHub Desktop.
A powershell module to keep a remote file up to date with a local copy via etag; e.g. IP lists
function Invoke-FileDownload {
param(
[Parameter(Mandatory=$true)]
[string]$Uri,
[Parameter(Mandatory=$true)]
[string]$OutFile,
[Parameter(Mandatory=$false)]
[hashtable]$Headers
)
$file = $Url -replace 'http(s)?://' -replace '/', '_'
$content = Invoke-WebRequest -Uri $Uri -Method Head -UseBasicParsing
if ($content.Headers.Etag) {
$TEMP = [System.Environment]::GetEnvironmentVariable('TEMP', 'Machine')
if (Test-Path "$TEMP/$file.etag") {
$storedtag = Get-Content "$TEMP/$file.etag"
if ($storedtag -eq $content.Headers.Etag) {
Write-Host "Etag is the same, no need to redownload!"
} else {
Write-Host "Etag changed! Redownloading content. Old Etag: $($storedtag), New Etag: $($content.Headers.Etag)"
Invoke-WebRequest -Uri "$Uri" -UseBasicParsing -OutFile "$OutFile" -Headers $Headers
Set-Content "$TEMP/$file.etag" -Value $content.Headers.Etag -NoNewline
}
} else {
Write-Host "No Etag file found!"
Invoke-WebRequest -Uri "$Uri" -UseBasicParsing -OutFile "$OutFile" -Headers $Headers
Set-Content "$TEMP/$file.etag" -Value $content.Headers.Etag -NoNewline
}
} else {
Write-Host "Server provided no Etag!"
Invoke-WebRequest -Uri "$Uri" -UseBasicParsing -OutFile "$OutFile" -Headers $Headers
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment