Copy-Item with timeout

前端 未结 1 1461
情深已故
情深已故 2020-12-21 09:15

I am recovering files from a hard drive wherein some number of the files are unreadable. I\'m unable to change the hardware level timeout / ERC, and it\'s extremely diffic

相关标签:
1条回答
  • 2020-12-21 09:58

    I'd say the canonical way of doing things like this in PowerShell are background jobs.

    $timeout = 300 # seconds
    
    $job = Start-Job -ScriptBlock { Copy-Item ... }
    Wait-Job -Job $job -Timeout $timeout
    Stop-Job -Job $job
    Receive-Job -Job $job
    Remove-Job -Job $job
    

    Replace Copy-Item inside the scriptblock with whatever command you want to run. Beware though, that all variables you want to use inside the scriptblock must be either defined inside the scriptblock, passed in via the -ArgumentList parameter, or prefixed with the using: scope qualifier.

    An alternative to Wait-Job would be a loop that waits until the job is completed or the timeout is reached:

    $timeout = (Get-Date).AddMinutes(5)
    do {
      Start-Sleep -Milliseconds 100
    } while ($job.State -eq 'Running' -and (Get-Date) -lt $timeout)
    
    0 讨论(0)
提交回复
热议问题