Private/Get-specEntraIDDeviceID.ps1

function Get-specEntraIDDeviceID {
    <#
    .SYNOPSIS
    Retrieves the most recent Entra ID (Azure AD) device ID from Microsoft Graph API by display name.
 
    .DESCRIPTION
    Queries Microsoft Graph API for devices matching the specified display name(s) and returns the ID of the most recently active device (based on approximateLastSignInDateTime).
    Handles cases where multiple device records exist with the same display name.
 
    .PARAMETER ComputerName
    One or more computer names (device display names) to look up. Accepts pipeline input and defaults to the local computer name.
 
    .PARAMETER AccessToken
    The OAuth 2.0 access token with permission to query Microsoft Graph API.
 
    .EXAMPLE
    Get-specEntraIDDeviceID -ComputerName "PC-123" -AccessToken $token
 
    .EXAMPLE
    "PC-123","PC-456" | Get-specEntraIDDeviceID -AccessToken $token
 
    .NOTES
    Author: owen.heaume
    Version: - 1.0.0 Initial release
             - 1.1.0 - Retrieves the most recent device ID in the event of duplicates.
                     - Updated comment-based help.
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]$ComputerName = $env:COMPUTERNAME,

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

    begin {
        $headers = @{ Authorization = "Bearer $AccessToken" }
    }

    process {
        foreach ($name in $ComputerName) {
            $url = "https://graph.microsoft.com/v1.0/devices?`$filter=displayName eq '$name'&`$select=id,displayName,deviceId,approximateLastSignInDateTime"

            try {
                $response = Invoke-RestMethod -Method Get -Uri $url -Headers $headers -ErrorAction Stop
                $devices = $response.value

                if (-not $devices) {
                    Write-Warning "No device found with display name '$name'."
                    continue
                }

                # Sort by most recent sign-in time
                $mostRecent = $devices | Sort-Object -Property approximateLastSignInDateTime -Descending | Select-Object -First 1

                [pscustomobject]@{
                    DisplayName = $mostRecent.displayName
                    DeviceId    = $mostRecent.id
                    LastSignIn  = $mostRecent.approximateLastSignInDateTime
                }
            } catch {
                Write-Warning "Failed to query device '$name'. Error: $($_.Exception.Message)"
            }
        }
    }
}