PowerShell 重試特定區塊腳本的函式
引用的函式
irm 'raw.githubusercontent.com/hunandy14/Invoke-Retry/main/Invoke-Retry.ps1'|iex
使用方法1
Invoke-Retry {
Get-Content "non-existing-file.txt"
} -FinallyScriptBlock {
Write-Host " 🔄 Running Cleanup"
} -MaxRetries 3 -DelaySeconds 1 -ErrorAction Stop
這是一個簡單的試錯,自動重試3次,每次1秒,然後最後面的 ErrorAction Stop 建議是設定一下避免出現預期之外的事情,內建很多函式只報錯並不會被 try 擷取到。
使用方法2
Invoke-Retry {
Get-Content "non-existing-file.txt"
} -FinallyScriptBlock {
Write-Host " 🔄 Running Cleanup"
} -RetryableErrors @(
[System.Management.Automation.ItemNotFoundException],
[System.IO.FileNotFoundException],
[System.IO.DirectoryNotFoundException]
) -MaxRetries 3 -DelaySeconds 1 -ErrorAction Stop
可以通過 RetryableErrors 指定特定錯誤才重試
沒有留言:
張貼留言