Search code examples
powershellloopsnetwork-driveretry-logic

How to add maximum looping in Powershell?


I would like to mapping the network. I need to use retry if the mapping fail, and the maximum retry 5 times. I've tried this way, but I can't figure out how to add the maximum retry.

Do{
    Try{     
        $net = new-object -ComObject WScript.Network                   
        $net.MapNetworkDrive("$Directory", "\\IP\$Folder", $False, "$Server\$SQL", "$pass")
        $Message = "Mapping : " + $Directory + "Successful"
        Write-Host $Message
        
    }
    Catch{

         $Message= "Mapping : " + $Directory + " Fault" + " $_"
         Write-Host $Message
         # in here there is error handling.
         CallErrorHandlingFunction
    }
}While($? -ne $true)

# in here there is next process after network mapping  succesfull.
CallNextProcess

Anyone can help really appreciated. Thanks


Solution

  • There are many ways to approach this, here is one using a script block, note that this example only works because you're using Write-Host which's outputs goes to the Information Stream and it's output is not captured unless redirected (6>&1).

    $action = {
        Try
        {
            $net = New-Object -ComObject WScript.Network                   
            $net.MapNetworkDrive(
                "$Directory", "\\IP\$Folder", $False, "$Server\$SQL", "$pass"
            )
            $Message = "Mapping : " + $Directory + "Successful"
            Write-Host $Message
            $true # => if everything goes right $result = $true
        }
        Catch
        {
            $Message = "Mapping : " + $Directory + " Fault" + " $_"
            Write-Host $Message
            $false # => if fails $result = $false
        }
    }
    
    $maxRetries = 5
    
    do { $result = & $action }             # do this
    until (-not --$maxRetries -or $result) # until $result is True OR
                                           # $maxRetries reaches 0
    

    Honestly a much easier alternative:

    $maxRetries = 5
    
    1..$maxRetries | ForEach-Object {
        if( & $action ) { break } # => if action = True stop the loop
    }