Primary User with Graph and PowerShell

Quick FYI: This post looks best in light mode. Use below controls to switch between light/dark mode! =)

😅 Getting the primary user of a device sounds easy enough, but there are scenarios where it could be hard to do it natively.

❓Want get the primary user of a device, search no more! In this post we will have a look at how to use Microsoft Graph and PowerShell to accomplish this.

Scenario

In this scenario I have used Microsoft Defender for EndPoint to export a list of all devices having old versions of Adobe Acrobat installed, to ask them to re-new their license, to get access to the latest (and secure) version.
But as the export doesn’t include any user info, it is hard to know who to email.
The list could be HUGE and it would require a lot of time to do this manually – good thing we have PowerShell close-by!

Prerequisites

If you have not currently registered an app to be used by PowerShell and Graph, please do so. Below post covers how to register the app and add API permissions (scroll down to “Register the app”.
Bitlocker Recovery Key Tool (nicklasahlberg.se)

This specific script will require the following API permissions (please add these before proceeding):

  • DeviceManagementManagedDevices.Read.All
  • DeviceManagementManagedDevices.ReadWrite.All

Solution

So, I saved the export to a .txt-file, including just the computer names.
Now all we need to do is:

  1. Copy below code to out favorite editor (I am using Visual Studio Code)
  2. Add our tenant ID to row 4
  3. Add our client ID to row 5
  4. Add the path to our .txt-file to row 18
  5. 😍 That is it. Now all we need to do is run the script and the $outputHash variable will hold all info

$ErrorActionPreference = 'SilentlyContinue'

$connectionDetails = @{
	'TenantID' = '%yourTenantIdGoesHere%'
	'ClientID' = '%yourClientIdGoesHere%'
}

$MSALToken = Get-MsalToken @connectionDetails
$token = $MSALToken.AccessToken

$filter = 'filter'
$deviceParameters = @{
	"apiURL" = "https://graph.microsoft.com/beta/deviceManagement/managedDevices?$filter=(deviceType eq 'windowsRT')"
	"method" = "Get"
}

$allDevices = (Invoke-RestMethod -Headers @{ Authorization = "Bearer ${token}" } -Uri $deviceParameters.apiURL -Method $deviceParameters.method).value
$allAdobeDevices = Get-Content -Path '%pathToTextFile%'
$outputHash = @{}

foreach ($device in $allAdobeDevices)
{

$deviceInfo = $allDevices | Where-Object {$_.deviceName -contains "$device"}
$outputHash.Add($deviceInfo.deviceName, $deviceInfo.userPrincipalName)

}

Leave a Reply

Your email address will not be published.