Velin Georgiev Blog

PowerShell retry logic code


This is a small PowerShell retry logic code snipet so I do not have to search for one ever again.


function Add-Package($SiteFullUrl, $Creds, $PackagePath) {

$stopLoop = $false
$retryCount = 0
do {
try {

# YOUR LOGIC HERE
Connect-PnPOnline $SiteFullUrl -Credentials $Creds
Add-PnPApp -Path $PackagePath -Scope Site -Publish -Overwrite -SkipFeatureDeployment -ErrorAction Stop
Write-Host "`Add-Package: Job completed for $PackagePath"

$stopLoop = $true
}
catch [Exception] {
if ($retryCount -gt 30){
Write-Host "Add-Package: Max retry for $PackagePath"
$stopLoop = $true
}
else {
Write-Host $_.Exception.Message -ForegroundColor Yello
Write-Host "Add-Package: Could not complete retrying in 10 seconds... $PackagePath"
Start-Sleep -Seconds 10
$retryCount = $retryCount + 1
}
}
} while ($stopLoop -eq $false)
}