-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathDownload-VerifiedFile.ps1
More file actions
74 lines (61 loc) · 2.61 KB
/
Download-VerifiedFile.ps1
File metadata and controls
74 lines (61 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#
# Develop a Windows PowerShell function that downloads a file to a target directory based on a specified URL and SHA-256 hash.
# The target directory can be specified as a parameter. If not provided, the default location will be $env:TEMP.
# The function should verify whether the file already exists. If the file is not present, it must be downloaded.
# After downloading, the function must compute the file's SHA-256 hash and compare it to the expected value. If the hashes do not match, an error should be raised.
# In cases where the file already exists but fails the hash validation, the function must re-download the file and overwrite the existing version.
#
# GitHub Copilot > Claude 3.7 Sonnet (Preview)
#
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Url,
[Parameter(Mandatory = $true)]
[string]$ExpectedHash,
[Parameter(Mandatory = $false)]
[string]$TargetDirectory = $env:TEMP
)
# Ensure target directory exists
if (-not (Test-Path -Path $TargetDirectory -PathType Container)) {
New-Item -Path $TargetDirectory -ItemType Directory -Force | Out-Null
Write-Verbose "Created directory: $TargetDirectory"
}
# Extract filename from URL
$fileName = [System.IO.Path]::GetFileName($Url)
$filePath = Join-Path -Path $TargetDirectory -ChildPath $fileName
# Flag to determine if download is needed
$downloadRequired = $true
# Check if file already exists
if (Test-Path -Path $filePath -PathType Leaf) {
Write-Verbose "File already exists: $filePath. Verifying hash..."
# Calculate hash of existing file
$fileHash = (Get-FileHash -Path $filePath -Algorithm SHA256).Hash
# Compare hash
if ($fileHash -eq $ExpectedHash) {
Write-Verbose "Hash verification successful for existing file."
$downloadRequired = $false
}
else {
Write-Warning "Existing file hash does not match expected hash. Re-downloading..."
}
}
# Download file if required
if ($downloadRequired) {
try {
Write-Verbose "Downloading $Url to $filePath..."
Invoke-WebRequest -Uri $Url -OutFile $filePath -UseBasicParsing
# Verify hash of downloaded file
$fileHash = (Get-FileHash -Path $filePath -Algorithm SHA256).Hash
if ($fileHash -ne $ExpectedHash) {
Remove-Item -Path $filePath -Force
throw "Downloaded file hash ($fileHash) does not match expected hash ($ExpectedHash)."
}
Write-Verbose "Download complete and hash verification successful."
}
catch {
throw "Failed to download or verify file: $_"
}
}
# Return the file path
return $filePath