Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API

Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API! In this article, we’ll explore how to remove the primary user from an Intune-managed device using its machine name, leveraging Microsoft Graph API and PowerShell scripting. This approach is particularly useful when transitioning devices into shared mode for environments like classrooms, kiosks, or frontline workstations. By automating this process, IT admins can streamline device provisioning and reduce manual overhead.

A primary user in Intune refers to the individual most closely associated with a specific device. Typically, when a device is enrolled, the first signed-in user becomes its primary user. This association is known as Device Affinity, and it plays a key role in user-targeted policies, app deployments, and reporting. The primary user is visible in the device’s properties and can be updated or removed as needed.

The primary user property also influences several user-facing and administrative experiences. It determines how devices appear in the Company Portal app, the end-user website, and IT troubleshooting tools in the Azure portal.

These experiences rely on accurate user-device mapping to deliver personalized content and efficient support. Ensuring the correct primary user or removing it when necessary is essential for maintaining a clean and functional Intune environment. In this article, I’ll demonstrate how to convert a test machine into a shared device by removing its primary user using a PowerShell script that interacts with Microsoft Graph API endpoints.

Patch My PC

Learn more About Shared Devices Concept

When a device has no primary user assigned, Intune classifies it as a Shared Device. Shared devices are ideal for multi-user scenarios where personalization isn’t required, such as classrooms, kiosks, or frontline workstations. Devices used by multiple individuals are commonly referred to as shared devices and are a standard component of mobile device management (MDM) solutions.

Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API. Fig-01
Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API. Fig-01

With Microsoft Intune, you can customize shared devices running platforms such as Windows 10 Professional and newer, Windows 10 Enterprise and newer, and Windows Holographic for Business (e.g., HoloLens). For instance, schools often deploy devices that are accessed by many students.

In such cases, the Intune administrator can enable the Shared PC feature to allow only one user to sign in at a time, preventing account switching between sessions.

When a student signs out, administrators can choose to remove all user-specific settings to maintain privacy and consistency. End users typically sign in to these shared devices using a guest account. Once signed in, their credentials are cached, and access is limited to only the features permitted by the administrator. For example, you can configure whether the device enters sleep mode, whether users can view or save files locally, and whether power management settings are enabled or disabled.

Additionally, you have control over how guest accounts are handled after sign-out. You can configure the device to delete the guest account upon sign-off or automatically remove inactive accounts once a defined threshold is reached. These settings help maintain a clean and secure shared environment, ensuring that each user session starts fresh and adheres to organizational policies.

Difference Between Primary User and Microsoft Entra Device Owner

In some cases, the Intune Primary user may differ from the Microsoft Entra device’s owner property, which is viewable under Devices > Microsoft Entra Devices. The Entra device owner is assigned during the device’s registration into Microsoft Entra ID and reflects the user who performed the initial join or registration.

For newly enrolled Microsoft Entra devices, the Owner property in Entra ID is typically set at the same time the Intune primary user is assigned. However, these two properties serve different purposes and may diverge over time depending on how the device is managed, reassigned, or used in shared scenarios.

Feature / RolePrimary User (Intune)Device Owner (Microsoft Entra)
DefinitionThe user most frequently associated with a device in Intune.The user who registered or joined the device to Microsoft Entra ID.
PurposeUsed for targeting policies, app deployments, and reporting in Intune.Determines ownership and access control in Microsoft Entra ID.
Assignment MethodCan be manually assigned or automatically determined based on usage.Automatically assigned during device registration or join process.
VisibilityShown in Intune portal under device properties.Shown in Microsoft Entra admin center under device details.
ChangeabilityCan be changed manually via Intune portal.Cannot be changed directly; requires re-registration or re-join.
Impact on ManagementInfluences app targeting, compliance policies, and user-based configurationsImpacts device lifecycle, access permissions, and conditional access policies.
Typical Use CaseAssigning apps or policies to the user most active on the device.Identifying who owns the device from an identity and access standpoint.
Shared DevicesDevices without a primary user are treated as shared.Shared devices may still have an Entra owner from initial registration
Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API (Table Courtesy – Microsoft. Table-01)

How to Remove a Primary User from Intune Portal

While most readers are likely familiar with the process of removing a Primary User from the Intune portal, I’d like to briefly explain it for those who may not be. It’s always beneficial to understand how the process works manually before introducing automation into your workflow.

NOTE! Intune automatically assigns a primary user to a device during or shortly after enrollment, depending on the enrollment method used.
  • Sign in to the Microsoft Intune Admin Portal with your credentials.
  • Select Devices > All devicesSelect the deviceProperties > Primary user
Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API. Fig-02
Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API. Fig-02

To remove the current primary user, click Remove primary user. To assign a different user as the primary user, click Change primary user and select the desired user from the list.

PlatformEnrollment methodPrimary user assignedPrimary user is assigned
WindowsAdd work or school (user driven)Enrolling userDuring enrollment
WindowsModern App sign-in (user driven)Enrolling userDuring enrollment
WindowsEnroll in mobile device management (MDM) only (user driven)Enrolling userDuring enrollment
WindowsMicrosoft Entra join (out of box experience)Enrolling userDuring enrollment
WindowsMicrosoft Entra join (Windows Autopilot out of box experience)Enrolling userDuring enrollment
WindowsEnroll in MDM onlyEnrolling userDuring enrollment
WindowsMicrosoft Entra hybrid join + automatic enrollment GPOFirst user to sign in to WindowsWhen first user signs in to Windows
WindowsCo-managementFirst user to sign in to WindowsWhen first user signs in to Windows
WindowsMicrosoft Entra join (bulk enrollment token)NoneNot applicable
WindowsMicrosoft Entra join (Windows Autopilot self-deploying mode)NoneNot applicable
Cross-platformUser driven enrollment with Company Portal AppEnrolling userDuring enrollment
Cross-platformDevice Enrollment Manager (DEM)Enrolling DEM userDuring enrollment
iOS/iPadOS, macOSApple Automated Device Enrollment (DEP with User Affinity)Enrolling userDuring enrollment
iOS/iPadOS, macOSApple Automated Device Enrollment (DEP without User Affinity)NoneNot applicable
AndroidAndroid Corporate-Owned, Dedicated devicesNoneNot applicable
Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API (Table Courtesy – Microsoft. Table-02

PowerShell Script to Remove Primary User from Intune Device

Well, Let’s learn how PowerShell Script can Remove Primary User from Intune Device and make you life eaiser. This automation requires Microsoft Graph PowerShell modules. The SDK includes two modules, Microsoft. Graph and Microsoft.Graph.Beta, are respectively called the Microsoft Graph REST API v1.0 and Microsoft Graph REST API beta.

Read more : Best Guide to Install Microsoft Graph PowerShell Modules

It’s important to understand the required permissions for removing a Primary User from an Intune device using the Graph API. You should need the DeviceManagementManagedDevices.ReadWrite.All permission to execute this automation successfully,

<#
.SYNOPSIS

Removes the Primary User from an Intune-managed device using its machine name.

.DESCRIPTION

This script connects to Microsoft Graph and removes the Primary User associated with a specified Intune device.
It identifies the device by its machine name, retrieves the current user association, and performs a DELETE operation via Graph API.
Designed for automation workflows, device cleanup, and user reassignment scenarios.

.AUTHOR

Sujin Nelladath — Microsoft Graph MVP

.PARAMETER MachineName

Mandatory. The name of the device from which the Primary User should be removed.

.EXAMPLE
Remove Primary User from a device named 'HR-Laptop-01':
.\Remove-IntunePrimaryUser.ps1 -MachineName "HR-Laptop-01"

.NOTES
Requires Microsoft.Graph modules and the DeviceManagementManagedDevices.ReadWrite.All permission scope.
Uses the beta endpoint for user removal via `$ref`.

#>




param
(
    [Parameter(Mandatory = $true)]
    [string]$MachineName
)

# Check if Microsoft Graph module is installed

if (!(Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
    Write-Error "Microsoft Graph module not installed. Run: Install-Module Microsoft.Graph"
    exit 1
}

# Import modules

Import-Module Microsoft.Graph.Authentication
Import-Module Microsoft.Graph.DeviceManagement

# Connect to Microsoft Graph
Write-Host "Connecting to Microsoft Graph..."
Connect-MgGraph -Scopes "DeviceManagementManagedDevices.ReadWrite.All"

# Find the device by name using Graph API

Write-Host "Looking for device: $MachineName"
$Uri = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?$filter=deviceName"
$Response = Invoke-MgGraphRequest -Method GET -Uri $Uri

$devicename = foreach ( $device in $Response.value)

{
   $device | Where-Object {$_.deviceName -eq $MachineName}
}

$deviceId = $devicename.id

if (!$devicename)
 {
    Write-Error "Device '$MachineName' not found in Intune"
    exit 1
}

Write-Host "Found device: $($devicename.deviceName) (ID: $($deviceId))"

# Get current primary users using Graph API

$UsersUri = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$($deviceId)')/users"
$UsersResponse = Invoke-MgGraphRequest -Method GET -Uri $UsersUri
$PrimaryUsers = $UsersResponse.value

if ($PrimaryUsers.Count -eq 0) 

{
    Write-Host "No primary users found for this device"
}

else 

{
    Write-Host "Found $($PrimaryUsers.Count) user associated with device"
    Write-Host ""$PrimaryUsers.displayName" is the primary using, the script will remove the user from the device" -ForegroundColor Yellow
    
    # Remove all user associations (there should only be one primary user max)

    try
    
    {
        # Remove primary user using simple DELETE to users/$ref endpoint
        $RemoveUri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices/$($deviceId)/users/`$ref"
        Invoke-MgGraphRequest -Method DELETE -Uri $RemoveUri
        
        Write-Host "Successfully removed primary user from device" -ForegroundColor Green
    }

    catch 
    {
        Write-Error "Failed to remove primary user: $($_.Exception.Message)" 
    }
}

Write-Host "Disconnecting from Microsoft Graph..."
Disconnect-MgGraph

Write-Host "Script completed."

PowerShell Script to Remove Primary Users from Multiple Intune Device

You may encounter scenarios where it becomes necessary to remove Primary Users from multiple Intune devices. In some cases, there could be hundreds of devices requiring this action. The script below demonstrates how to remove Primary Users from multiple Intune devices efficiently.

<#

.SYNOPSIS

Removes the Primary User from one or more Intune-managed devices using a list of machine names.

.DESCRIPTION

This script connects to Microsoft Graph and removes the Primary User associated with each specified Intune device.
It reads device names from a text file, retrieves the current user association, and performs a DELETE operation via Graph API.
Designed for automation workflows, bulk device cleanup, and user reassignment scenarios.

.AUTHOR
Sujin Nelladath — Microsoft Graph MVP

.PARAMETER DeviceListPath

Mandatory. Path to the text file containing device names (one per line).

.EXAMPLE

Remove Primary Users from devices listed in C:\Temp\devices.txt:
.\Remove-IntunePrimaryUsers.ps1 -DeviceListPath "C:\Temp\devices.txt"

.NOTES

Requires Microsoft.Graph modules and the DeviceManagementManagedDevices.ReadWrite.All permission scope.
Uses the beta endpoint for user removal via `$ref`.

#>

param
(
    [Parameter(Mandatory = $true)]
    [string]$DeviceListPath
)

# Check if Microsoft Graph module is installed
if (!(Get-Module -ListAvailable -Name Microsoft.Graph.Authentication))

{
    Write-Error "Microsoft Graph module not installed. Run: Install-Module Microsoft.Graph"
    exit 1
}

# Import modules
Import-Module Microsoft.Graph.Authentication
Import-Module Microsoft.Graph.DeviceManagement

# Connect to Microsoft Graph
Write-Host "Connecting to Microsoft Graph..."
Connect-MgGraph -Scopes "DeviceManagementManagedDevices.ReadWrite.All"

# Read device names from file
$DeviceNames = Get-Content -Path $DeviceListPath

foreach ($MachineName in $DeviceNames) 

{
    Write-Host "Processing device: $MachineName"

    # Find the device by name
    $Uri = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?$filter=deviceName eq '$MachineName'"
    $Response = Invoke-MgGraphRequest -Method GET -Uri $Uri

    $devicename = $Response.value | Where-Object { $_.deviceName -eq $MachineName }
    $deviceId   = $devicename.id

    if (!$devicename) 
    
    {
        Write-Error "Device '$MachineName' not found in Intune"
        continue
    }

    Write-Host "Found device: $($devicename.deviceName) (ID: $($deviceId))"

    # Get current primary users
    $UsersUri = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$($deviceId)')/users"
    $UsersResponse = Invoke-MgGraphRequest -Method GET -Uri $UsersUri
    $PrimaryUsers = $UsersResponse.value

    if ($PrimaryUsers.Count -eq 0) 
    
        {
            Write-Host "No primary users found for this device"
        }

    else
    
     {
        Write-Host "Found $($PrimaryUsers.Count) user(s) associated with device"
        Write-Host "$($PrimaryUsers.displayName) will be removed as primary user" -ForegroundColor Yellow

        try 
        
            {
                # Remove primary user
                $RemoveUri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices/$($deviceId)/users/`$ref"
                Invoke-MgGraphRequest -Method DELETE -Uri $RemoveUri
                Write-Host "Successfully removed primary user from device" -ForegroundColor Green
            }
        catch 
        
            {
                Write-Error "Failed to remove primary user: $($_.Exception.Message)"
            }
    }
}

Write-Host "Disconnecting from Microsoft Graph..."
Disconnect-MgGraph

Write-Host "Script completed."

End-Result

I have executed the PowerShell script to remove the Primary User from an Intune device. To verify the result, log in to the Microsoft Intune portal with your credentials and navigate to Devices > All devices > Select the device > Properties > Primary user.

Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API 1
Automate the Process of Removing Primary User from Intune Device using Microsoft Graph API. Fig-03

I trust that this article will significantly benefit you and your organization. I appreciate your patience in reading this post. I look forward to seeing you in the next post. Keep supporting the HTMD Community.

Download the Scripts

For your ease of doing, I uploaded the both powerShell scripts in Github reporsty, I request you to go the below links and download it if you need it.

Remove a Primay User from Intune Portal : Download 
Remove Primary Users from Multiple Intune Device : Download

Need Further Assistance or Have Technical Questions?

Join the LinkedIn Page and Telegram group to get the latest step-by-step guides and news updates. Join our Meetup Page to participate in User group meetings. Also, Join the WhatsApp Community to get the latest news on Microsoft Technologies. We are there on Reddit as well.

Author

About the Author: Sujin Nelladath, Microsoft Graph MVP with over 11 years of experience in SCCM device management and Automation solutions, writes and shares his experiences with Microsoft device management technologies, Azure, DevOps and PowerShell automation.

Leave a Comment