简体   繁体   English

循环获取邮箱 cmdlet,直到没有错误返回

[英]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.我有混合设置,共享邮箱在几分钟内在本地创建并同步到 Exchange Online。 My routine is to create a shared mailbox on-prem and then convert it, populate, enable messagecopy, etc. through Connect-ExchangeOnline.我的套路是在本地创建一个共享邮箱,然后通过Connect-ExchangeOnline对其进行转换、填充、启用messagecopy等。

I want to have a tiny script to check if it synced to EO or not.我想要一个小脚本来检查它是否同步到 EO。 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.我尝试了几种不同的方法,看起来这个方法应该有效,但不幸的是,它在成功或错误后中断,而没有像我期望的那样在 10 秒内尝试运行 get-mailbox。 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
        }
}

As commented, to catch also non-terminating exceptions, you must use -ErrorAction Stop .如评论所述,要捕获非终止异常,您必须使用-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{..}或者,如果你想使用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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM