Functions/Block-UntilExchangeOnlineUserAvailable.ps1

<#
.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.'"
}