,

Intune and Powershell: Bulk update Windows primary user by last logged on user

This script does the following:

  1. Connects to Microsoft Graph with the necessary permissions.
  2. Defines two functions:
    • Get-LastLoggedOnUser: Retrieves the last logged-on user for a given device.
    • Set-PrimaryUser: Sets the primary user for a given device.
  3. Retrieves all Windows devices managed by Intune.
  4. For each device:
    • Gets the last logged-on user.
    • If a last logged-on user is found and is different from the current primary user, it updates the primary user.

To use this script:

  1. Ensure you have the Microsoft.Graph PowerShell module installed and the necessary permissions in Azure AD/Intune.
  2. Run the script in a PowerShell environment with administrator privileges.

This script should meet your requirements by processing all Windows Intune managed devices, identifying the last logged-on user for each, and updating the primary user if necessary.

  1. Process all Windows Intune managed devices
  2. Identify the last logged-on user for each device
  3. Update the primary user to the last logged-on user if they’re different

This approach ensures that the primary user in Intune always reflects the most recent user of each device, which can be crucial for accurate device management and reporting.

A few things to keep in mind as you use this script:

  1. Make sure you run it regularly to keep the primary user information up-to-date.
  2. Monitor the script’s output for any devices that consistently fail to update or don’t have a last logged-on user. This could indicate issues with those devices that may need further investigation.
  3. Ensure that the account running the script maintains the necessary permissions in Microsoft Graph to read device information and update primary users.

Here it is:

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "DeviceManagementManagedDevices.ReadWrite.All", "User.Read.All"

function Get-LastLoggedOnUser {
    param (
        [string]$DeviceId
    )
    try {
        $uri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices('$DeviceId')?`$select=id,deviceName,usersLoggedOn"
        $device = Invoke-MgGraphRequest -Uri $uri -Method GET

        if ($device.usersLoggedOn -and $device.usersLoggedOn.Count -gt 0) {
            # Sort users by last login time and get the most recent one
            $lastUser = $device.usersLoggedOn | Sort-Object -Property lastLogOnDateTime -Descending | Select-Object -First 1
            return $lastUser.userId
        }
        return $null
    }
    catch {
        Write-Host "Error getting last logged on user for device $DeviceId : $_" -ForegroundColor Red
        return $null
    }
}

function Set-PrimaryUser {
    param (
        [string]$DeviceId,
        [string]$UserId
    )
    try {
        $uri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices('$DeviceId')/users/`$ref"
        $body = @{
            "@odata.id" = "https://graph.microsoft.com/beta/users('$UserId')"
        } | ConvertTo-Json

        Invoke-MgGraphRequest -Uri $uri -Method POST -Body $body -ContentType "application/json"
        return $true
    }
    catch {
        Write-Host "Error setting primary user for device $DeviceId : $_" -ForegroundColor Red
        return $false
    }
}

# Get all Windows Intune Managed Devices
$devices = Get-MgDeviceManagementManagedDevice -Filter "operatingSystem eq 'Windows'"

foreach ($device in $devices) {
    Write-Host "Processing device: $($device.DeviceName)" -ForegroundColor Cyan

    # Get the last logged on user
    $lastUserId = Get-LastLoggedOnUser -DeviceId $device.Id
    if ($lastUserId) {
        $lastUser = Get-MgUser -UserId $lastUserId
        Write-Host "Last logged on user: $($lastUser.UserPrincipalName)" -ForegroundColor Yellow

        # Check if the current primary user is different from the last logged on user
        if ($device.UserPrincipalName -ne $lastUser.UserPrincipalName) {
            Write-Host "Updating primary user..." -ForegroundColor Yellow
            $result = Set-PrimaryUser -DeviceId $device.Id -UserId $lastUserId
            if ($result) {
                Write-Host "Primary user updated successfully to $($lastUser.UserPrincipalName)" -ForegroundColor Green
            }
            else {
                Write-Host "Failed to update primary user" -ForegroundColor Red
            }
        }
        else {
            Write-Host "Primary user is already set to the last logged on user" -ForegroundColor Green
        }
    }
    else {
        Write-Host "No last logged on user found for this device" -ForegroundColor Yellow
    }

    Write-Host ""
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph

Hope it helps you to manage your Intune Windows Devices. 🙂

About me

Over 20 years working with IT for multiple fields (logistics, Olympic games, oil and gas, insurance, pharmaceuticals, etc).

Sometimes find solutions on the internet can be challenging. That’s why I decided to create techmission.ca, where I’ll gather some solutions I have to apply on my environments as I receive my “missions” (that’s the way I name client’s requests).

Hope the solutions published here can help you guys as it helps me 🙂

Featured Posts