0

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
        }
}
nekku
  • 3
  • 1
  • I'm not familiar with it, but it sounds like even if `$ID` doesn't exist `Get-Mailbox` doesn't throw an error for `catch` to...catch. Maybe it needs to be `$mailbox = Get-MailBox $ID; if ($null -ne $mailbox) { $mailbox; break } else { Start-Sleep 10 }`. – Lance U. Matthews Mar 28 '22 at 06:22
  • If your intent is to catch errors in the `catch` block, then set `$ErrorActionPreference = 'Stop'`. This will make sure also non-terminating exceptions are handled there – Theo Mar 28 '22 at 09:36

1 Answers1

0

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
    }
}
Theo
  • 57,719
  • 8
  • 24
  • 41
  • Thanks a lot, both worked! I actually don't know much about try/catch yet and was simply experimenting based on googling. And it's hard to google people wanting to use it for purposes opposite to its intent as you can imagine. Once again, thank you very much, I will use your answer to understand more about how powershell handles errors and what is terminating and non-terminating error and how they're handled. – nekku Mar 28 '22 at 23:05