Functions/Get-IntuneLoggedOnUsers.ps1


function Get-IntuneLoggedOnUsers {
    [CmdletBinding()]
    param (
        # [Parameter()] [string] $ParameterName
    )

    Write-Verbose "Get Intune Devices"
    $DeviceList = Invoke-MSGraphRequest -Url "https://graph.microsoft.com/beta/deviceManagement/managedDevices" | Get-MSGraphAllPages

    $DeviceList = $DeviceList | Where-Object operatingSystem -EQ "Windows"

    # $DeviceList = $DeviceList | Select-Object -Last 10

    Write-Verbose "Get Autopilot Devices"
    $AutopilotDevices = Get-AutopilotDevice

    Write-Verbose "Get Azure AD Users"
    # $AzureAdUsers = Get-AzureADUser -all $true
    $AzureAdUsers = Get-MgUser -All
    # $AzureAdUsers

    $Result = @()

    Write-Verbose "Processing data"
    foreach ($d in $DeviceList) {

        # Write-Output $d.deviceName

        $CurrentAutopilotDevice = $AutopilotDevices | Where-Object serialNumber -EQ $d.serialNumber

        # $i++
        # Write-Progress -Activity "Processing" -CurrentOperation "$($d.DeviceName) ($($i) / $($DeviceList.count))" -PercentComplete ( ($i / ($DeviceList.count) * 100) )

        foreach ($usersLoggedOn in $d.usersLoggedOn) {

            # Write-Output $usersLoggedOn.userId
            # Write-Output $usersLoggedOn.lastLogOnDateTime


            $CurrentUser = $AzureAdUsers | Where-Object Id -EQ $usersLoggedOn.userId
            # Write-Output $CurrentUser.DisplayName


            $Properties = [ordered]@{
                DeviceName         = $d.DeviceName
                UserPrincipalName  = $CurrentUser.UserPrincipalName
                UserDisplayName    = $CurrentUser.DisplayName
                lastLogOnDateTime  = $usersLoggedOn.lastLogOnDateTime
                DevicePrimaryUser  = $d.userPrincipalName
                DeviceSerialNumber = $d.serialNumber
                AutopilotGroupTag  = $CurrentAutopilotDevice.groupTag
            }

            $Result += New-Object -TypeName PSCustomObject -Property $Properties

        }



    }

    $Result = $Result | Sort-Object lastLogOnDateTime

    return $Result

}