Private/DownloadFilesSequentially.ps1

function DownloadFilesSequentially {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [System.Collections.ArrayList]
        $FileInfoList,

        [Parameter(Mandatory)]
        [string]
        $OutputPath
    )

    $currentDownloadNumber = 0
    $totalUpdateFiles = $FileInfoList.Count

    foreach ($parsedFileInfo in $FileInfoList) {
        $currentDownloadNumber += 1
        $downloadProgress = "$currentDownloadNumber/$totalUpdateFiles"

        $fileDownloadUri = $parsedFileInfo["Uri"]
        $fileName = $parsedFileInfo["FileName"]
        $fileDownloadPath = Join-Path $OutputPath $fileName -ErrorAction Stop
        $fileDownloadPathTemp = "$fileDownloadPath.tmp"

        if (Test-Path $fileDownloadPath) {
            Write-Output "Skipping already downloaded update file $fileName ($downloadProgress)."
            continue
        }

        if (Test-Path $fileDownloadPathTemp) {
            Write-Output "Restarting download for incomplete update file $fileName ($downloadProgress)..."

            try {
                Remove-Item -Path $fileDownloadPathTemp -ErrorAction Stop
            } catch {
                Write-Error -Message "Could not remove incomplete update file ($fileDownloadPathTemp). Please remove this file manually and try again."
                return
            }
        } else {
            Write-Output "Downloading update file $fileName ($downloadProgress)..."
        }

        try {
            $transferParams = GetBitsTransferSplatBase -Source $fileDownloadUri
            Start-BitsTransfer @transferParams `
                -DisplayName "Import-WsusUpdate update file download ($downloadProgress)" `
                -Destination $fileDownloadPathTemp `
                -ErrorAction Stop
        } catch {
            Write-Warning "BITS transfer for update file $fileName failed with the following error: $_"
            Write-Verbose "Full error info:"
            Write-Verbose ($_ | Format-List -Force | Out-String)
            Write-Warning "Retrying download once more with Invoke-WebRequest as a fallback..."

            try {
                $webRequestParams = GetWebRequestSplatBase -Uri $fileDownloadUri
                $webRequestParams["OutFile"] = $fileDownloadPathTemp
                Invoke-WebRequest @webRequestParams -ErrorAction Stop
            } catch {
                Write-Warning "Fallback download also failed for update file $fileName (URI: $fileDownloadUri) with the following error: $_"
                throw
            }
        }

        Write-Verbose "Moving finished download to its proper path $fileDownloadPath."
        Move-Item -Path $fileDownloadPathTemp -Destination $fileDownloadPath -ErrorAction Stop
    }
}

# Copyright (c) 2023 AJ Tek Corporation. All Rights Reserved.