Powershell Try Catch用于在复制期间检测usb枚举

时间:2015-09-16 09:02:08

标签: powershell try-catch

camelCase

在这里,我能够捕获异常并显示"未找到驱动器"

但我的问题是,一旦驱动器目的地可用,我希望副本继续。有可能吗?

所有帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

这样的事可以帮助你:

$VerbosePreference = 'Continue'

$RetryCount = 0; $MaxTries = 5; $Completed = $false

$Source = 'C:\Users\...\Desktop\1gb'
$Destination = 'F:\'

while (-not $Completed) {
    Try {
        Copy-Item -LiteralPath $Source -Destination $Destination -Recurse -Force -ErrorAction Stop
        $Completed = $true
    }
    Catch {
        if ($RetryCount -ge $MaxTries) {
            Write-Verbose 'Drive not found'
            throw "Drive not found Source '$($Source)' > '$($Destination)': $($Global:Error[0].Exception.Message)"
        } 
        else {
            Write-Verbose "Drive not found, retrying in 5 seconds."
            Start-Sleep -Seconds 5
            $RetryCount++
        }
    }
}

基本上它每5秒重试一次,如果它第6次失败,它将抛出错误并停止所有动作。您可以将其修改为分钟,小时......以满足您的需求。