Functions/Block-UntilMSOnlineUserAvailable.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
<#
.SYNOPSIS
    This function waits for a user to become available on MS Online.
.DESCRIPTION
    This function waits for a user to become available on MS Online.
    This function assumes that the connection to MS Online has already been
    previously established before this function was called.
    Returns the retrieved user object.
#>

function Block-UntilMSOnlineUserAvailable {
    [CmdletBinding(PositionalBinding=$true)]
    [OutputType([PSObject])]
    param (
        # The user to wait for
        [Parameter(Mandatory=$true)]
        [String]$userPrincipalName,

        # The maximum amount of time to wait (in seconds)
        # Defaults to 1 minute (60 seconds)
        [Parameter(Mandatory=$false)]
        [Int32]$waitLimit = 60
    )

    # Keep trying to retrieve the user
    $user = $null
    for ($waitCount = 0; ; $waitCount += 1) {
        # Waited too long for user
        if ($waitCount -ge $waitLimit) {
            Write-Error "Waited the maximum amount of time for '$($userPrincipalName)' to become available."
            return $null
        }

        # Try to retrieve the user
        $user = Get-MsolUser -SearchString $userPrincipalName -ErrorAction SilentlyContinue

        # Check if retrieved user is valid
        if ($null -ne $user -and $user.UserPrincipalName -eq $userPrincipalName) {
            return $user
        }

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