Param($url, $downloadDir, $sha1hash, $sha256hash) if ($PSBoundParameters.Count -lt 4) { Write-host "Error: -Url -DownloadDir -Sha1hash -Sha256hash " ;exit 1} If ( -not (Test-Path $downloadDir)) { Write-host "Error: -DownloadDir does not exist." ;exit 1} function Write-Log { param ( [string]$Message, [string]$LogPath = "$env:TEMP\downloadandcheck_updates.log" ) #Output to Console Write-Host $Message $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $entry = "[$timestamp] $Message" Add-Content -Path $LogPath -Value $entry } $LogPath = ".\downloadandcheck_updates.logg" if (Test-Path $logPath) { $logTime = (get-item $logPath).LastWriteTime } else { $logTime = get-Date("1900/1/1") } Write-Log -Message "Start downloadandcheck_updates.ps1" -LogPath $LogPath $downloadStatus = $false $downloaduri = $url $filename = Split-Path $downloaduri -Leaf if (Test-Path (Join-Path $downloadDir $filename)) { Write-Log -Message "File $($filename) has already beed downloaded. Skip download." -LogPath $LogPath } else { Write-Log -Message "Downloading $($filename) ..." -LogPath $LogPath Invoke-WebRequest -Uri $downloaduri -OutFile (Join-Path $downloadDir $filename) -UseBasicParsing if (Test-Path (Join-Path $downloadDir $filename)) { $downloadStatus = $true Write-Log -Message "Download completed." -LogPath $LogPath } else { Write-Log -Message "Download failed." -LogPath $LogPath } } $hashStatus = $true $downloadedfile = Join-Path $downloadDir $filename if ($downloadStatus) { $bytes = [IO.File]::ReadAllBytes($downloadedfile) $sha256 = [Security.Cryptography.SHA256]::Create() $h256 = $sha256.ComputeHash($bytes) $h256_b64 = [Convert]::ToBase64String($h256) $sha1 = [Security.Cryptography.SHA1]::Create() $h1 = $sha1.ComputeHash($bytes) $h1_b64 = [Convert]::ToBase64String($h1) if ($sha1hash) { if (!($sha1hash -ceq $h1_b64)) { $hashStatus = $false } if($hashStatus) { Write-Log -Message "SHA1 Hash OK" -LogPath $LogPath } else { Write-Log -Message "SHA1 Hash NG" -LogPath $LogPath } } if ($sha256hash) { if ($sha256hash -ceq $h256_b64) { if (!($hashStatus)) { Write-Log -Message "SHA256 Hash NG" -LogPath $LogPath $hashStatus = $false } } else { $hashStatus = $false } if($hashStatus) { Write-Log -Message "SHA256 Hash OK" -LogPath $LogPath } else { Write-Log -Message "SHA256 Hash NG" -LogPath $LogPath } } if (!($hashStatus)) { Remove-Item $downloadedfile Write-Log -Message "Hash Check NG, Remove downloaded file." -LogPath $LogPath } }