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

関連情報