<# .SYNOPSIS .EXAMPLE PowerShell.exe IEX (IRM intuneaadcleanup.osdcloud.ch) .DESCRIPTION .NOTES Version: 0.9 Creation Date: 13-03-2023 Author: Akos Bakos Company: SmartCon GmbH Contact: akos.bakos@smartcon.ch Copyright (c) 2023 SmartCon GmbH HISTORY: Date By Comments ---------- --- ---------------------------------------------------------- 26.05.2023 Akos Bakos Force to connect MSGraph + AzureAD 08.06.2023 Akos Bakos Migrate AzureAD module to Graph API 21.08.2023 Akos Bakos Get-Manufacturer query change (CIM --> WMI) 21.08.2023 Akos Bakos Get Microsoft Entra ID object #> $Global:Transcript = "$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Cleanup-IntuneAADAutopilot_Objects.log" Start-Transcript -Path (Join-Path "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\OSD\" $Global:Transcript) -ErrorAction Ignore $env:Path += ";C:\Program Files\WindowsPowerShell\Scripts" # Enable TLS 1.2 support for downloading modules from PSGallery (Required) [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Write-Host "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass" Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force Write-Host "`n=========================================`n" Write-Host "Importing modules" -ForegroundColor Yellow # Get NuGet $Provider = Get-PackageProvider NuGet -ErrorAction Ignore if (-not $Provider) { Write-Host "Installing provider NuGet" Find-PackageProvider -Name NuGet -ForceBootstrap -IncludeDependencies } # Get WindowsAutopilotIntune module (and dependencies) $Module = Import-Module WindowsAutopilotIntune -PassThru -ErrorAction Ignore if (-not $Module) { Write-Host "Installing module WindowsAutopilotIntune" Install-Module WindowsAutopilotIntune -Force -WarningAction:Ignore } Import-Module WindowsAutopilotIntune -Scope Global -Force # Get Microsoft.Graph.Identity.DirectoryManagement module if needed $Module = Import-Module Microsoft.Graph.Identity.DirectoryManagement -PassThru -ErrorAction Ignore if (-not $Module) { Write-Host "Installing module Microsoft.Graph.Identity.DirectoryManagement" Install-Module Microsoft.Graph.Identity.DirectoryManagement -Force -WarningAction:Ignore } Import-Module Microsoft.Graph.Identity.DirectoryManagement -Scope Global -Force # Get Microsoft.Graph.DeviceManagement module if needed $Module = Import-Module Microsoft.Graph.DeviceManagement -PassThru -ErrorAction Ignore if (-not $Module) { Write-Host "Installing module Microsoft.Graph.DeviceManagement" Install-Module Microsoft.Graph.DeviceManagement -Force -WarningAction:Ignore } Import-Module Microsoft.Graph.DeviceManagement -Scope Global -Force # Connect try { Write-Host "`n=========================================`n" Write-Host "Grabbing PFX certificate for the authentication" -ForegroundColor Yellow $subjectName = "PSPAutopilotRegistration" $Cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object { $_.Subject -Match "$subjectName" } If (!$Cert) { Write-Host "Cannot find the proper certificate --> cannot connect to the tenant!" -ForegroundColor Red Return } $TenantID = "66bed719-f928-4d2d-88c4-2086a9f02a13" $AppID = "bb0e4ec7-e09b-4ce6-90f6-d4763c2b466b" Connect-MgGraph -Tenant $TenantId -AppId $AppId -Certificate $Cert | Out-Null Write-Host "Connected to Intune tenant " -NoNewline Write-Host "$TenantId " -ForegroundColor Cyan -NoNewline Write-Host "using cert-based authentication" Update-MSGraphEnvironment -SchemaVersion beta -Quiet } catch { Write-Host "Cannot connect to MS Graph" -ForegroundColor Red Write-Host "Error!" –ForegroundColor Red Write-Host "$($_.Exception.Message)" –ForegroundColor Red Return } # Declare variables $TargetIntuneMachine = @() $TargetAutopilotMachineSN = $null $TargetAADMachine = @() $SerialNR = $null $AutopilotDevice = $null Write-Host "`n=========================================`n" Write-Host "Grabbing the computer information" -ForegroundColor Yellow $SerialNR = Get-WmiObject Win32_BIOS | Select-Object serialnumber -ExpandProperty serialnumber Write-Host "Serial number is: " -NoNewline Write-Host "$SerialNR" -ForegroundColor Cyan # Checking if the machine is a virtual one from VMware $MyComputerManufacturer = ((Get-WMIObject -Class Win32_ComputerSystem).Manufacturer).Trim() Write-Host "Host manufacturer: " -NoNewline Write-Host "$MyComputerManufacturer" -ForegroundColor Cyan if ($MyComputerManufacturer -match 'Dell') { $MyComputerManufacturer = 'Dell' } if ($MyComputerManufacturer -match 'Lenovo') { $MyComputerManufacturer = 'Lenovo' } if ($MyComputerManufacturer -match 'Hewlett') { $MyComputerManufacturer = 'HP' } if ($MyComputerManufacturer -match 'Packard') { $MyComputerManufacturer = 'HP' } if ($MyComputerManufacturer -match 'HP') { $MyComputerManufacturer = 'HP' } if ($MyComputerManufacturer -match 'Microsoft') { $MyComputerManufacturer = 'Microsoft' } if ($MyComputerManufacturer -match 'Panasonic') { $MyComputerManufacturer = 'Panasonic' } if ($MyComputerManufacturer -match 'to be filled') { $MyComputerManufacturer = 'OEM' } if ($null -eq $MyComputerManufacturer) { $MyComputerManufacturer = 'OEM' } $Get_Manufacturer_Info = $MyComputerManufacturer if ($Get_Manufacturer_Info -like "*VMware*") { $TargetAutopilotMachineSN = $SerialNR.Replace(' ', '') } else { $TargetAutopilotMachineSN = $SerialNR } Write-Host "`n=========================================`n" Write-Host "Retrieving Intune device record" -ForegroundColor Yellow try { $TargetIntuneMachine = Get-MgDeviceManagementManagedDevice -Filter ("SerialNumber eq '$TargetAutopilotMachineSN'") } catch { Write-Host "Unable to get Intune object" -ForegroundColor Red Write-Host "Error!" –ForegroundColor Red Write-Host "$($_.Exception.Message)" –ForegroundColor Red Return } if ($TargetIntuneMachine) { Write-Host "We are talking about this Intune device:" -ForegroundColor Cyan Write-Host ($TargetIntuneMachine | Format-List | Out-String) try { Write-Host "Deleting DeviceName: " -NoNewline Write-Host "$($TargetIntuneMachine.deviceName) | Id: $($TargetIntuneMachine.Id) | AzureADDeviceId: $($TargetIntuneMachine.azureADDeviceId) | SerialNumber: $($TargetIntuneMachine.serialNumber)" -ForegroundColor Cyan Remove-MgDeviceManagementManagedDevice -ManagedDeviceId $TargetIntuneMachine.Id while (Get-MgDeviceManagementManagedDevice -Filter ("SerialNumber eq '$TargetAutopilotMachineSN'")) { Write-Host "Waiting for deletion..." Start-Sleep -Seconds 10 } Write-Host "Intune object has been deleted" -ForegroundColor Green } catch { Write-Host "Unable to remove Intune object" -ForegroundColor Red Write-Host "Error!" –ForegroundColor Red Write-Host "$($_.Exception.Message)" –ForegroundColor Red Return } } else { Write-Host "This Intune device doesn't exist" -ForegroundColor Red } Write-Host "`n=========================================`n" Write-Host "Retrieving Autopilot device record" -ForegroundColor Yellow $AutopilotDevice = Get-AutopilotDevice -serial $SerialNR If ($AutopilotDevice) { Try { Write-Host "Deleting SerialNumber: " -NoNewline Write-Host "$($AutopilotDevice.serialNumber) | Model: $($AutopilotDevice.model) | Id: $($AutopilotDevice.id) | GroupTag: $($AutopilotDevice.groupTag)" -ForegroundColor Cyan Remove-AutopilotDevice $AutopilotDevice.id while (Get-AutopilotDevice | Get-MSGraphAllPages | Where-Object { $_.serialNumber -eq $SerialNR }) { Write-Host "Waiting for deletion..." Start-Sleep -Seconds 10 } Write-Host "Autopilot object has been deleted" -ForegroundColor Green } Catch { Write-Host "Unable to delete the Autopilot object" -ForegroundColor Red Write-Host "Error!" –ForegroundColor Red Write-Host "$($_.Exception.Message)" –ForegroundColor Red Return } } else { Write-Host "This Autopilot device doesn't exist" -ForegroundColor Red } Write-Host "`n=========================================`n" Write-Host "Retrieving Microsoft Entra ID device record" -ForegroundColor Yellow try { $TargetAADMachine = Get-MgDevice -All | Where-Object {$_.DeviceId -eq "$($TargetIntuneMachine.AzureAdDeviceId)"} } catch { Write-Host "Unable to get Microsoft Entra ID object" -ForegroundColor Red Write-Host "Error!" –ForegroundColor Red Write-Host "$($_.Exception.Message)" –ForegroundColor Red Return } if ($TargetAADMachine) { Write-Host "We are talking about this Microsoft Entra ID device:" -ForegroundColor Cyan Write-Host ($TargetAADMachine | Format-List | Out-String) try { Write-Host "Deleting DisplayName: " -NoNewline Write-Host "$($TargetAADMachine.DisplayName) | ObjectId: $($TargetAADMachine.Id) | DeviceId: $($TargetAADMachine.DeviceId)" -ForegroundColor Cyan Remove-MgDevice -DeviceId $TargetAADMachine.Id while (Get-MgDevice -All | Where-Object {$_.DeviceId -eq "$($TargetIntuneMachine.AzureAdDeviceId)"}) { Write-Host "Waiting for deletion..." Start-Sleep -Seconds 10 } Write-Host "Microsoft Entra ID object has been deleted" -ForegroundColor Green } catch { Write-Warning "Unable to remove Microsoft Entra ID object" Write-Host "Error!" –ForegroundColor Red Write-Host "$($_.Exception.Message)" –ForegroundColor Red Return } } else { Write-Host "This Microsoft Entra device doesn't exist" -ForegroundColor Red } Write-Host "`n=========================================`n" Write-Host "Some cleanup task" -ForegroundColor Yellow Write-Host "Disconnect Graph API" Disconnect-MgGraph | Out-Null Write-Host "Delete certificate from local machine store" $subjectName = "PSPAutopilotRegistration" $cert = (Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object { $_.Subject -Match "$subjectName" }).Thumbprint Remove-Item -Path Cert:\LocalMachine\My\$cert -Force Write-Host "`n=========================================`n" Stop-Transcript