Functions/Remove-IntunePrimaryUser.ps1
function Remove-IntunePrimaryUser { [CmdletBinding(SupportsShouldProcess)] param ( [Parameter(Mandatory)] [string[]] $UserPrincipalNames ) Write-Verbose "Retreiving all Intune devices..." $Devices = Get-MgDeviceManagementManagedDevice -All $FilteredDevices = @() foreach ($upn in $UserPrincipalNames) { $FilteredDevices += $Devices | Where-Object UserPrincipalName -EQ $upn } # $FilteredDevices | Select-Object DeviceName, UserPrincipalName $FilteredDevices | ForEach-Object { $uri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices('$($_.Id)')/users" $primaryUser = Invoke-MgGraphRequest -Uri $uri -Method Get -Verbose:$false # $primaryUser # $primaryUser.value.userPrincipalName if ($primaryUser.value.userPrincipalName -eq $_.UserPrincipalName) { if ($PSCmdlet.ShouldProcess("$($_.DeviceName) - $($primaryUser.value.userPrincipalName)")) { $DeleteUri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices('$($_.Id)')/users/`$ref" Write-Output "Device: $($_.DeviceName) - Removing primary user: $($primaryUser.value.userPrincipalName)" Invoke-MgGraphRequest -Uri $DeleteUri -Method DELETE } } } } |