#requires -Version 5.1 <# Infostruction enrollment cleanup, revision 2026-11-03. Default: inventory only. -Apply requires one explicit enrollment GUID and its exact UPN. This is a last-resort local cleanup of historical registry entries and scheduled tasks, not a supported Intune unenrollment method and not proof that an enrollment is stale. Backups are required before changes. They contain device/user information; protect them. Examples: .\Intune-Enrollment-Cleanup.ps1 .\Intune-Enrollment-Cleanup.ps1 -EnrollmentId 'GUID' -ExpectedUpn 'old@example.com' -Apply -WhatIf .\Intune-Enrollment-Cleanup.ps1 -EnrollmentId 'GUID' -ExpectedUpn 'old@example.com' -Apply #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] param( [string]$EnrollmentId, [string]$ExpectedUpn, [switch]$Apply, [string]$BackupRoot = (Join-Path $env:ProgramData 'Infostruction\EnrollmentBackups') ) function Assert-EnrollmentEnvironment { if ($env:OS -ne 'Windows_NT') { throw 'Windows is required.' } if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { throw 'Use 64-bit PowerShell on a 64-bit Windows installation.' } $identity = [Security.Principal.WindowsIdentity]::GetCurrent() if (-not ([Security.Principal.WindowsPrincipal]$identity).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Open PowerShell as administrator to inspect all enrollment tasks and apply cleanup.' } } function Get-EnrollmentInventory { $root = 'HKLM:\SOFTWARE\Microsoft\Enrollments' if (-not (Test-Path -LiteralPath $root)) { return } foreach ($key in Get-ChildItem -LiteralPath $root -ErrorAction Stop) { $parsed = [guid]::Empty if ([guid]::TryParse($key.PSChildName, [ref]$parsed)) { $properties = Get-ItemProperty -LiteralPath $key.PSPath -ErrorAction Stop [pscustomobject]@{ EnrollmentId=$key.PSChildName; UPN=$properties.UPN } } } } function Get-EnrollmentCleanupPlan { param([string]$EnrollmentId, [string]$ExpectedUpn, [string]$ObservedUpn, [object[]]$Tasks=@()) if ($EnrollmentId -notmatch '^(\{[0-9a-fA-F-]{36}\}|[0-9a-fA-F-]{36})$') { throw 'Supply one complete enrollment GUID, not a path or wildcard.' } $parsed = [guid]::Empty if (-not [guid]::TryParse($EnrollmentId, [ref]$parsed) -or $parsed -eq [guid]::Empty) { throw 'Invalid enrollment GUID.' } if ([string]::IsNullOrWhiteSpace($ExpectedUpn) -or $ExpectedUpn -ine $ObservedUpn) { throw 'The enrollment UPN does not match ExpectedUpn. No changes made.' } $roots = @( 'HKLM:\SOFTWARE\Microsoft\Enrollments', 'HKLM:\SOFTWARE\Microsoft\Enrollments\Status', 'HKLM:\SOFTWARE\Microsoft\EnterpriseResourceManager\Tracked', 'HKLM:\SOFTWARE\Microsoft\PolicyManager\AdmxInstalled', 'HKLM:\SOFTWARE\Microsoft\PolicyManager\Providers', 'HKLM:\SOFTWARE\Microsoft\Provisioning\OMADM\Accounts', 'HKLM:\SOFTWARE\Microsoft\Provisioning\OMADM\Logger', 'HKLM:\SOFTWARE\Microsoft\Provisioning\OMADM\Sessions' ) $canonical = $parsed.ToString('D') $taskPaths = @("\Microsoft\Windows\EnterpriseMgmt\$canonical\", "\Microsoft\Windows\EnterpriseMgmt\{$canonical}\") [pscustomobject]@{ EnrollmentId=$EnrollmentId UPN=$ObservedUpn RegistryPaths=@($roots | ForEach-Object { "$_\$EnrollmentId" }) Tasks=@($Tasks | Where-Object { $_.TaskPath -iin $taskPaths }) } } function New-EnrollmentBackup { param($Plan, [string]$BackupRoot) $directory = Join-Path ([IO.Path]::GetFullPath($BackupRoot)) ((Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N')) [void](New-Item -ItemType Directory -Path $directory -ErrorAction Stop) # Set access before writing potentially sensitive registry exports. $acl = Get-Acl -LiteralPath $directory $acl.SetAccessRuleProtection($true,$false) $operatorSid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value foreach ($sid in @('S-1-5-18','S-1-5-32-544',$operatorSid) | Select-Object -Unique) { $rule = New-Object Security.AccessControl.FileSystemAccessRule( (New-Object Security.Principal.SecurityIdentifier($sid)), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow') $acl.AddAccessRule($rule) } Set-Acl -LiteralPath $directory -AclObject $acl -ErrorAction Stop $index = 0 foreach ($key in $Plan.RegistryPaths) { if (Test-Path -LiteralPath $key) { $index++ $native = $key -replace '^HKLM:', 'HKEY_LOCAL_MACHINE' & "$env:SystemRoot\System32\reg.exe" export $native (Join-Path $directory "registry-$index.reg") /y | Out-Null if ($LASTEXITCODE -ne 0) { throw "Registry export failed for $key. Cleanup aborted before deletion." } } } $index = 0 foreach ($task in $Plan.Tasks) { $index++ Export-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -ErrorAction Stop | Set-Content -LiteralPath (Join-Path $directory "task-$index.xml") -Encoding Unicode -ErrorAction Stop } $Plan | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $directory 'manifest.json') -Encoding UTF8 -ErrorAction Stop $directory } function Invoke-EnrollmentCleanup { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] param([string]$EnrollmentId, [string]$ExpectedUpn, [switch]$Apply, [string]$BackupRoot=(Join-Path $env:ProgramData 'Infostruction\EnrollmentBackups')) Assert-EnrollmentEnvironment $inventory = @(Get-EnrollmentInventory) if (-not $Apply) { Write-Verbose 'Inventory only. A UPN is not evidence that an enrollment is stale.' return $inventory } $matches = @($inventory | Where-Object { $_.EnrollmentId -ieq $EnrollmentId }) if ($matches.Count -ne 1) { throw 'EnrollmentId must match exactly one inventory entry. Copy it from the inventory output.' } $plan = Get-EnrollmentCleanupPlan -EnrollmentId $matches[0].EnrollmentId -ExpectedUpn $ExpectedUpn -ObservedUpn $matches[0].UPN -Tasks @(Get-ScheduledTask -ErrorAction Stop) if (-not $PSCmdlet.ShouldProcess($plan.EnrollmentId, 'Back up, then remove only this enrollment registry data and its scheduled tasks')) { return $plan } $backupDirectory = New-EnrollmentBackup -Plan $plan -BackupRoot $BackupRoot # Recheck identity after backup, before the first deletion. $current = Get-ItemProperty -LiteralPath "HKLM:\SOFTWARE\Microsoft\Enrollments\$($plan.EnrollmentId)" -ErrorAction Stop if ($current.UPN -ine $ExpectedUpn) { throw 'Enrollment identity changed during backup. Cleanup aborted.' } foreach ($task in $plan.Tasks) { Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -Confirm:$false -ErrorAction Stop } foreach ($key in $plan.RegistryPaths) { if (Test-Path -LiteralPath $key) { Remove-Item -LiteralPath $key -Recurse -Force -ErrorAction Stop } } # Never delete raw files or folders from System32\Tasks. [pscustomobject]@{EnrollmentId=$plan.EnrollmentId;Result='Local cleanup completed; enrollment not yet verified';BackupDirectory=$backupDirectory} } if ($MyInvocation.InvocationName -ne '.') { Invoke-EnrollmentCleanup @PSBoundParameters }