I am trying to get my head around exception handling in Powershell, more specifically how to use a for loop to retry an action if it fails.
I have the code below, which catches the exception but will only attempt one iteration of the for loop.
Am I doing something wrong in my for loop? Or is this the behaviour of the catch block not to handle loops?
try{
Copy-Item "C:\Path\To\Source.file" "C:\Path\To\Destination.file" -Force -ErrorAction Stop
}
catch{
$e = $_.Exception.GetType().Name
LogWrite $e
if($e -eq 'IOException')
{
for($i=0; $i -lt 6; $i++)
{
LogWrite "Waiting..."
Start-Sleep -s 10
LogWrite "Copying in the file attempt $i"
Copy-Item "C:\Path\To\Source.file" "C:\Path\To\Destination.file" -Force
}
}
}
$e -eq 'IOException'gets false. What you see as "1 iteration" isLogWrite $e.