Search code examples
azureazure-active-directoryazure-powershellmicrosoft-entra-id

Microsoft Graph API, PowerShell code to get a list of compliant devices for a user


I am trying to come up with PowerShell code to get a list of compliant devices for a given user. So far, I have below code working to get the list of computers for a given user:

Connect-AzureAD
Connect-MgGraph 
$user = 'FName LName'
$user = Get-MgUser -Filter "Displayname eq '$user'"
$PrincipalName = $user.UserPrincipalName
$Id = $user.Id
Write-Host User Principal Name: $PrincipalName
Write-Host User Id: $Id
$devices = Get-MgUserOwnedDevice -UserId $Id
foreach ($device in $devices) {
        Write-Host "Device Id: $($device.Id)"
$test = get-MgDevice -DeviceId $device.Id 
Write-Host $test.DisplayName
}

But I would also like to include a filter to the get-MgDevice cmdlet to get only the compliant devices.

I tried to replace

$test = get-MgDevice -DeviceId $device.Id

with this one:

$test = Get-MgDevice -Filter 'isCompliant eq true' -ConsistencyLevel eventual -CountVariable c  -DeviceId $deviceId

But it doesn't work and errors out. Could someone suggest how I can accomplish my goal? Any help is very much welcome and appreciated. Thanks


Solution

  • I have one user named Sri with 2 devices where 1 is complaint among them like this:

    enter image description here

    When I ran your code to list the devices of given user, I got response like this:

    Connect-MgGraph -NoWelcome
    $user = 'Sri'
    $user = Get-MgUser -Filter "Displayname eq '$user'"
    $PrincipalName = $user.UserPrincipalName
    $Id = $user.Id
    Write-Host User Principal Name: $PrincipalName
    Write-Host User Id: $Id
    $devices = Get-MgUserOwnedDevice -UserId $Id
    foreach ($device in $devices) {
            Write-Host "Device Id: $($device.Id)"
    $test = get-MgDevice -DeviceId $device.Id 
    Write-Host $test.DisplayName
    }
    

    Response:

    enter image description here

    To get a list of only compliant devices for a given user, you can make use of below modified PowerShell script:

    Connect-MgGraph -NoWelcome
    
    $userName = 'Sri'
    $user = Get-MgUser -Filter "Displayname eq '$userName'"
    $userId = $user.Id
    
    Write-Host "User Principal Name: $($user.UserPrincipalName)"
    Write-Host "User Id: $($userId)"
    
    $devices = Get-MgUserOwnedDevice -UserId $userId
    
    $compliantDevices = 0
    
    foreach ($device in $devices) {
        $deviceId = $device.Id
        $test = Get-MgDevice -Filter "id eq '$deviceId' and isCompliant eq true"
        
        if ($test) {
            $compliantDevices++
            Write-Host "Device Id: $($test.Id)"
            Write-Host "Device Name: $($test.DisplayName)"
        }
    }
    
    Write-Host "Number of Compliant Devices: $($compliantDevices)"
    

    Response:

    enter image description here