Functions/Block-UntilExchangeOnlineGroupAvailable.ps1
<#
.SYNOPSIS This function waits for a group to become available on Exchange Online. .DESCRIPTION This function waits for a group to become available on Exchange Online. It assumes that the connection to Exchange Online has already been previously established before the function is called. It returns the retrieved group object if the group is available. If the group cannot be found within the maximum amount of time defined, it returns null. #> function Block-UntilExchangeOnlineGroupAvailable { [CmdletBinding(PositionalBinding=$true)] [OutputType([Object])] param ( # The identity of the group to wait for. [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()] [String]$identity, # The maximum amount of time to wait for the group to become available. # Defaults to 1 minute (60 seconds) [Parameter(Mandatory=$false)] [ValidateScript({ $_ -gt 0 })] [Int32]$waitLimitSeconds = 60, # The interval between attempts to retrieve the group. # Defaults to 1 second. [Parameter(Mandatory=$false)] [ValidateScript({ $_ -gt 0 })] [Int32]$waitIntervalSeconds = 1, # The type of the group. [Parameter(Mandatory=$false)] [ValidateSet("DistributionGroup", "DynamicDistributionGroup")] [String]$groupType = "DistributionGroup", # Select the stream where the failure messages will be directed. [Parameter(Mandatory=$false)] [ValidateSet("Information", "Warning", "Error")] [String]$outputStream = "Error" ) # Keep trying to retrieve the group $endTime = (Get-Date).AddSeconds($waitLimitSeconds) while ((Get-Date) -lt $endTime) { # Try to retrieve the group try { if ($groupType -eq "DistributionGroup") { $group = Get-Group -Identity $identity -ErrorAction Stop } else { $group = Get-DynamicDistributionGroup -Identity $identity -ErrorAction Stop } } catch { # Do nothing with the exception } # Retrieved the group if ($group) { return $group } # Wait for 1 second then try again Start-Sleep -Seconds $waitIntervalSeconds } # The group is still not available when the maximum time has elapsed Invoke-Expression "Write-$($outputStream) 'Waited the maximum amount of time for group $($identity) to become available.'" } |