Monday, February 10, 2025

Microsoft Graph, AppProfile, PowerShell to dump list of devices and last sync to Intune

 
  # You need an appProfile with intune permissions
$tenantId = 'xxxxxxxxxxxx' # You Tenant ID
$appId = 'xxxxxxxxxxxxx'  # Application (client) ID
$appSecret = 'xxxxxxxxxxxxxx' #Value

$body = @{  
    grant_type    = "client_credentials"  
    scope = "https://graph.microsoft.com/.default"  
    client_id     = $appId  
    client_secret = $appSecret  
}  
 
$response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"  
$token = $response.access_token  

# connecting as the application with the permission on the service
Connect-MgGraph -AccessToken ($Token |ConvertTo-SecureString -AsPlainText -Force)  
#disConnect-MgGraph

# (get-mgcontext).Scopes
#  (get-mgcontext)
   if (get-mgcontext) {write-host "Connected to O365" -ForegroundColor Green}
   else { write-host "Disconnected from O365" -ForegroundColor Red  break}

#  Get-MgDeviceManagementManagedDevice
  $devices = Get-MgDeviceManagementManagedDevice  -all # Can be long
 
# Filter devices where the OperatingSystem property contains "Windows"  
    $devices.Count
    $windowsDevices = $devices | Where-Object {  $_.OperatingSystem -like '*Windows*'  }  
    $windowsDevices.Count
   
    # Write-Host ($windowsDevices[22] | Format-List | Out-String) # Check one

$windowsDevices | ForEach-Object {   
    # Format the LastSyncDateTime as YYYYMMDD  
    $formattedDate = $_.LastSyncDateTime.ToString("yyyy-MM-dd")  
      
    # Write the output with the formatted date  
    Write-Host 'PCName;'$($_.DeviceName)';OS;'$($_.OSVersion)';LastSync;'$formattedDate';UserUPN;'$($_.UserPrincipalName)';Model;'$($_.model)';DeviceID;'$($_.Id)
}  
 

No comments:

Blog Archive