Get-MsalAccount.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
<#
.SYNOPSIS
    Get user from token cache of application.
.DESCRIPTION
 
.EXAMPLE
    PS C:\>$ClientApplication = Get-MsalClientApplication -ClientId '00000000-0000-0000-0000-000000000000'
    PS C:\>$ClientApplication | Get-MsalAccount
    Get all accounts from client application cache.
#>

function Get-MsalAccount {
    param
    (
        # Client application
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='ClientApplication', Position=0)]
        [Microsoft.Identity.Client.IClientApplicationBase] $ClientApplication,
        # Information of a single account.
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName='Accounts', Position=0)]
        [Microsoft.Identity.Client.IAccount[]] $Accounts,
        # The username in UserPrincipalName (UPN) format.
        [Parameter(Mandatory=$false)]
        [string] $Username
    )

    if ($PSCmdlet.ParameterSetName -eq 'ClientApplication') {
        [Microsoft.Identity.Client.IAccount[]] $Accounts = $ClientApplication.GetAccountsAsync().GetAwaiter().GetResult()
    }

    if ($Username) {
        return $Accounts | Where-Object Username -eq $Username
    }
    else {
        return $Accounts
    }
}