You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为无验证证书服务器的文件下载添加Try-Catch校验?

解决PowerShell下载无SSL证书文件的偶发失败问题

问题背景

尝试从无有效SSL证书的网站下载zip文件,已通过自定义证书策略忽略SSL警告,也添加了TLS协议支持,但脚本仍偶发报错:

ERROR: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
ERROR: Exception calling ".ctor" with "3" argument(s): "End of Central Directory record could not be found."

需要通过Try-Catch机制确保文件下载完成且可用后,再执行后续操作。

解决方案:带重试与完整性验证的下载脚本

可以通过Try-Catch捕获异常、重试机制自动恢复,再加上ZIP文件完整性校验,确保下载的文件可用。修改后的脚本如下:

###################### Download ###################### 
## download zipped files from WebPage/download (No Valid SSL Certificate)
$myDownloadUrl = 'www.SomeWebPage.com/Download/MyFiles.zip'

## installation folder (always under %appdata%\Company\MyFolder)
$myZipFile = "MyFiles.zip"
$installdir = "\Company\MyFolder\"
$myInstallDir = -join @($env:APPDATA, $installdir)
$myFilePath = -join@($myInstallDir, $myZipFile)

## make sure the folder exists
New-Item -ItemType Directory -Force -Path $myInstallDir

## Skip certificate (silently ignore duplicate type errors)
$code= @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;
        public class TrustAllCertsPolicy : ICertificatePolicy {
            public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) {
                return true;
            }
        }
"@
Add-Type -TypeDefinition $code -Language CSharp -ErrorAction SilentlyContinue
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

## Set supported SSL/TLS protocols (include TLS 1.3 for better compatibility)
$AllProtocols = [System.Net.SecurityProtocolType]'Tls,Tls11,Tls12,Tls13'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

## Download with retry and integrity validation
$maxRetries = 3
$retryCount = 0
$downloadSuccess = $false

while (-not $downloadSuccess -and $retryCount -lt $maxRetries) {
    try {
        $retryCount++
        Write-Host ">>> Downloading the Files (Attempt $retryCount of $maxRetries)..."
        
        # Delete corrupted file if exists
        if (Test-Path $myFilePath) {
            Remove-Item $myFilePath -Force
        }

        # Execute download, fail fast on errors
        Invoke-WebRequest -Uri $myDownloadUrl -OutFile $myFilePath -ErrorAction Stop

        # Validate ZIP file integrity
        try {
            $zipArchive = [System.IO.Compression.ZipFile]::OpenRead($myFilePath)
            $zipArchive.Dispose()
            Write-Host ">>> Download and ZIP validation successful!"
            $downloadSuccess = $true
        }
        catch {
            Write-Warning ">>> Downloaded file is corrupted: $_"
            throw "Corrupted ZIP file detected"
        }
    }
    catch {
        Write-Warning ">>> Download failed: $_"
        if ($retryCount -lt $maxRetries) {
            Write-Host ">>> Retrying in 5 seconds..."
            Start-Sleep -Seconds 5
        }
        else {
            Write-Error ">>> All $maxRetries download attempts failed. Exiting script."
            exit 1
        }
    }
}

# Post-download operations go here (only runs if download succeeded)
Write-Host ">>> Starting post-download tasks..."

核心改进说明

  • 嵌套Try-Catch:外层处理连接中断等下载异常,内层验证ZIP文件结构是否完整
  • 自动重试:最多重试3次,每次失败后等待5秒再尝试,应对临时网络波动
  • 损坏文件清理:重试前删除已损坏的文件,避免残留文件干扰后续下载
  • 扩展协议支持:添加TLS 1.3,提升与现代服务器的兼容性
  • 清晰状态反馈:打印重试次数、成功/失败信息,方便排查问题

内容的提问来源于stack exchange,提问作者M--

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 23:00:00