Hi guys, I want to create a function that will be checking execution of selected commands and in case of catched failure retry 3 times and display the command name with the retry message. I placed a test command "Test Connection" between the function brackets to be evaluted, retry seems to be working, however I can not get the command name to be printed. I tried with "$($MyInvocation.MyCommand.ScriptBlock)", but it prints out the whole function intead of that executed line that I'm checking. Can anyone please advice here? Thanks a lot in advance
function Execute-WithRetry([ScriptBlock]$command) {
$Stoploop = $false
$count = 0
do {
try {
& $command
Write-Host "Download completed"
$Stoploop = $true
}
catch {
if ($count -eq 3) {
Write-Host "Could not download after 3 retries."
$Stoploop = $true
}
else {
Write-Host "Could not download the files retrying in 5 seconds..."
Write-Host "Executing: $($MyInvocation.MyCommand.ScriptBlock)"
Start-Sleep -Seconds 5
}
}
$count++
}
While ($Stoploop -eq $false)
pause
}
Execute-WithRetry {
Test-Connection -ComputerName 192.10.129.15 -ErrorAction Stop
}
$MyInvocation.LineLineproperty contains a string - the line on which the statement that threw the error starts. Try grabbing the invocation info directly from the error record if$MyInvocationisn't giving you anything:try {Test-Connection nonexistingfqdn -ErrorAction Stop}catch {Write-Host "Failed at '$($_.InvocationInfo.Line |% Trim)'"}