Set Entra ID device user / owner

This script changes the user displayed in Entra ID. For the sake of simplicity, it changes both user and owner, but may be easily coerced

PowerShell
#
# Examples:
#
# Set-EntraDeviceOwner -DeviceName "DEV-E-0001" -UserPrincipalName $null
# Set-EntraDeviceOwner -DeviceName "DEV-E-0001" -UserPrincipalName "jkowalski@example.com"
#
#

function Set-EntraDeviceUser {
    param(
        [Parameter(Mandatory = $true)][string] $DeviceName,
        [Parameter(Mandatory = $true)][AllowEmptyString()][string] $UserPrincipalName
    )

    $deviceId = (Get-MgDevice -Filter "displayname eq '$DeviceName'").Id

    # Remove owners
    Get-MgDeviceRegisteredOwner -DeviceId $deviceId | Foreach-Object {
        Remove-MgDeviceRegisteredOwnerDirectoryObjectByRef -DeviceId $deviceId -DirectoryObjectId $_.Id | Out-Null
    }

    # Remove users
    Get-MgDeviceRegisteredUser -DeviceId $deviceId | Foreach-Object {
        Remove-MgDeviceRegisteredUserDirectoryObjectByRef -DeviceId $deviceId -DirectoryObjectId $_.Id | Out-Null
    }

    if ($UserPrincipalName) {
        $userObject = Get-MgUser -Filter "userprincipalname eq '$UserPrincipalName'"

        if (!$userObject) {
            Write-Error "User not found"

            return 1
        }

        $userId = $userObject.Id
            
        $params = @{
            "@odata.id" = "https://graph.microsoft.com/v1.0/directoryObjects/$userId"
        }

        New-MgDeviceRegisteredOwnerByRef -DeviceId $deviceId -BodyParameter $params | Out-Null
        New-MgDeviceRegisteredUserByRef -DeviceId $deviceId -BodyParameter $params | Out-Null
    }
}

Report of users and owners:

PowerShell
#
# Get-EntraDeviceState -DeviceName "DEV-E-0001"
# Get-MgDevice -Filter "startswith(displayname,'DEV-E-')" | ForEach-Object { Get-EntraDeviceState -DeviceName $_.DisplayName }
#

function Get-EntraDeviceState {
    param(
        [Parameter(Mandatory = $true)][string] $DeviceName
    )

    $device = Get-MgDevice -Filter "displayname eq '$DeviceName'"

    $ownerList = @()
    Get-MgDeviceRegisteredOwner -DeviceId $device.Id | ForEach-Object {
        $ownerList += ($_ | Select-Object -ExpandProperty AdditionalProperties)['userPrincipalName']
    }

    $userList = @()
    Get-MgDeviceRegisteredUser -DeviceId $device.Id | ForEach-Object {
        $userList += ($_ | Select-Object -ExpandProperty AdditionalProperties)['userPrincipalName']
    }

    $response = [PSCustomObject]@{
        Name   = $device.DisplayName
        Owners = $ownerList -join ' , '
        Users  = $userList -join ' , '
        Id     = $device.Id
    }

    return $response
}