Functions/Block-UntilExchangeOnlineGroupAvailable.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<#
.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.'"
}