在powershell中,如果檔案尚不存在,如何在一段時間後重試下載

在powershell中,如果檔案尚不存在,如何在一段時間後重試下載

我有一個 powershell 腳本,可以下載以下檔案:

powershell -Command `$progressPreference = 'silentlyContinue'; Invoke-WebRequest https://ftp.ncep.noaa.gov/data/nccf/com/cfs/prod/cfs/cfs.$m2/$m21z/6hrly_grib_04/pgbf$m2h.04.$m2h.grb2 -OutFile C:\OpenGrADS-2.2\data\cfs\cfs001.grb2`

是否可以在下載前檢查文件是否存在,如果存在則下載,如果不存在則等待一定時間再重試。

答案1

以下 PowerShell 腳本可以完成這項工作。

這是從貼文複製的 下載具有重試支援的遠端文件:

# $ErrorActionPreference = "Stop"
 
function DownloadWithRetry([string] $url, [string] $downloadLocation, [int] $retries)
{
    while($true)
    {
        try
        {
            Invoke-WebRequest $url -OutFile $downloadLocation
            break
        }
        catch
        {
            $exceptionMessage = $_.Exception.Message
            Write-Host "Failed to download '$url': $exceptionMessage"
            if ($retries -gt 0) {
                $retries--
                Write-Host "Waiting 10 seconds before retrying. Retries left: $retries"
                Start-Sleep -Seconds 10
 
            }
            else
            {
                $exception = $_.Exception
                throw $exception
            }
        }
    }
}
 
#
# Usage
DownloadWithRetry -url "http://example.com/file.zip" -downloadLocation "C:\Downloads\file.zip" -retries 6

相關內容