Search code examples
powershellmicrosoft-exchange

Loop get-mailbox cmdlet until no error returned


I have hybrid setup where shared mailboxes are getting created on-prem and synced through to Exchange Online in a span of couple of minutes. My routine is to create a shared mailbox on-prem and then convert it, populate, enable messagecopy, etc. through Connect-ExchangeOnline.

I want to have a tiny script to check if it synced to EO or not. I've tried several different ways and seemingly this one should work, but unfortunately it breaks after both success or error without attempting to run get-mailbox in 10 seconds as I expect it to. Please review and advise.

$ErrorActionPreference = 'SilentlyContinue'
$ID = "xxx@yyy"

$i=0
while ($i -le 10) {
    try {
        Get-Mailbox $ID 
        break
        }
    catch { 
        $i++
        $i
        Start-Sleep 10
        }
}

Solution

  • As commented, to catch also non-terminating exceptions, you must use -ErrorAction Stop.

    But why not simply do something like

    $ID = "xxx@yyy"
    
    for ($i = 0; $i -le 10; $i++) {  #  # loop 11 attempts maximum
        $mbx = Get-Mailbox -Identity $ID -ErrorAction SilentlyContinue
        if ($mbx) {
            Write-Host "Mailbox for '$ID' is found" -ForegroundColor Green
            break
        }
        Write-Host "Mailbox for '$ID' not found.. Waiting 10 more seconds"
        Start-Sleep -Seconds 10
    }
    

    Or, if you want to use try{..} catch{..}

    $ID = "xxx@yyy"
    
    for ($i = 0; $i -le 10; $i++) {  # loop 11 attempts maximum
        try {
            $mbx = Get-Mailbox -Identity $ID -ErrorAction Stop
            Write-Host "Mailbox for '$ID' is found" -ForegroundColor Green
            $i = 999  # exit the loop by setting the counter to a high value
        }
        catch {
            Write-Host "Mailbox for '$ID' not found.. Waiting 10 more seconds"
            Start-Sleep -Seconds 10
        }
    }