Public/Get-specEntraIDUser.ps1

Function Get-specEntraIdUser {
    <#
    .SYNOPSIS
    Retrieves user information from Microsoft Graph API based on UserPrincipalName (UPN) using an access token.
 
    .DESCRIPTION
    This function retrieves user information from Microsoft Graph API based on the specified UserPrincipalName (UPN). It requires an access token with appropriate permissions to access Microsoft Graph.
 
    .PARAMETER UPN
    Specifies the UserPrincipalName (UPN) of the user(s) whose information is to be retrieved. This parameter accepts input from the pipeline. If not specified, the default value is set to the UPN of the currently logged-in user.
 
    .PARAMETER AccessToken
    Specifies the access token required to authenticate with Microsoft Graph API. This parameter is mandatory.
 
    .EXAMPLE
    Get-specEntraIdUser -UPN "user1@specsavers.com" -AccessToken "your_access_token_here"
    Retrieve information for a single user with the specified UPN.
 
    .EXAMPLE
    "user1@specsavers.com" | Get-specEntraIdUser -AccessToken "your_access_token_here"
    Retrieve information for a single user using pipeline input for the UPN.
 
    .EXAMPLE
    $customObject = [pscustomobject]@{
        UPN = "user1@specsavers.com"
        AccessToken = "your_access_token_here"
    }
    $customObject | Get-specEntraIdUser
    Retrieve information for user(s) whose UPNs are contained in a custom object sent through the pipeline.
 
    .NOTES
    Author: owen.heaume
    Version: 1.0.0
    #>


    [cmdletbinding()]
    param(
        [parameter(Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('UserPrincipalName')]
        [string[]]$UPN = "$ENV:USERNAME@specsavers.com",

        [parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$AccessToken
    )

    Begin {
    }

    process {
        foreach ($user in $UPN) {
            $url = "https://graph.microsoft.com/v1.0/users?`$filter=userPrincipalName eq '$user'&`$select=displayname,givenname,surname,mail,officelocation,department,id"
            try {
                $result = Invoke-RestMethod -Method Get -Uri $url -Headers @{Authorization = "Bearer $($AccessToken)" } -ea Stop
            } catch {
                Write-Warning "$User Error: $($_.Exception.Message)"
                continue
            }

            $result.value | % { [pscustomobject]@{
                    displayName    = $_.displayname
                    givenName      = $_.givenname
                    surname        = $_.surname
                    mail           = $_.mail
                    officeLocation = $_.officelocation
                    department     = $_.department
                    id             = $_.id
                }
            }
        }
    }
}