Functions/Block-UntilExchangeOnlineUserAvailable.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
<#
.SYNOPSIS
    This function waits for a user to become available on Exchange Online.
.DESCRIPTION
    This function waits for a user 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 user object if the user is available.
    If the user cannot be found within the maximum amount of time defined, it returns null.
#>

function Block-UntilExchangeOnlineUserAvailable {
    [CmdletBinding(PositionalBinding=$true)]
    [OutputType([Object])]
    param (
        # The identity of the user to wait for.
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateNotNullOrEmpty()]
        [String]$identity,

        # The maximum amount of time to wait for the user 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 user.
        # Defaults to 1 second.
        [Parameter(Mandatory=$false)]
        [ValidateScript({ $_ -gt 0 })]
        [Int32]$waitIntervalSeconds = 1,

        # 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 user
    $endTime = (Get-Date).AddSeconds($waitLimitSeconds)
    while ((Get-Date) -lt $endTime) {
        # Try to retrieve the user
        try {
            $user = Get-User -Identity $identity -ErrorAction Stop
        }
        catch {
            # Do nothing with the exception
        }

        # Retrieved the user
        if ($user) {
            return $user
        }

        # Wait for 1 second then try again
        Start-Sleep -Seconds $waitIntervalSeconds
    }

    # The user is still not available when the maximum time has elapsed
    Invoke-Expression "Write-$($outputStream) 'Waited the maximum amount of time for user $($identity) to become available.'"
}