Re-Enrolling a Workstation into Intune using PowerShell

Why is the Intune Client Unhealthy?

In large enterprise environments, maintaining the health of Intune clients can be challenging due to several factors that may disrupt endpoint connectivity. Common reasons for an endpoint to become unhealthy with Intune include network connectivity issues, where unstable or misconfigured networks prevent proper communication between the endpoint and Intune services. Firewall or proxy settings can also block required traffic, leading to failed updates or policy applications. Additionally, outdated or incompatible operating systems and software can cause synchronization failures. Misconfigured device compliance policies might incorrectly mark devices as non-compliant, while corrupted Intune client installations can lead to frequent errors and communication breakdowns. Furthermore, certificate issues, such as expired or incorrectly issued certificates, can hinder secure connections. Understanding and addressing these potential issues is crucial for maintaining robust Intune client health in enterprise environments.

What Information is Needed to Remove the Intune Client?

While scouring the internet for solutions, I found a great blog post by Maxime Rastello that helped me manually re-enroll the workstation into Intune. Un-enrolling the endpoint requires you to remove various scheduled tasks and registry keys associated with the Intune enrollment using the Enrollment ID. To find the enrollment ID, you can use various methods.

Registry Keys

Look for the enrollment ID as a GUID nested in any of these registry keys:

  • 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\

You can search for a registy item to extract the enrollment id.

try{

$enrollmentId = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Provisioning\OMADM\Logger\" -Name "CurrentEnrollmentId"

}catch{}

Scheduled Tasks

Since we need to remove scheduled tasks before we remove the registry keys, you can search for the ID in the scheduled tasks with some regex.

$intuneScheduledTasks = Get-ScheduledTask -TaskPath "\Microsoft\Windows\EnterpriseMgmt\*" | ? {$_.TaskPath -match '([0-9A-Fa-f]){8}-(([0-9A-Fa-f]){4}-){3}([0-9A-Fa-f]){11}'}

$enrollmentId = ($intuneScheduledTasks[0].TaskPath).TrimEnd("\").split("\")[-1]

That regex expression '([0-9A-Fa-f]){8}-(([0-9A-Fa-f]){4}-){3}([0-9A-Fa-f]){11}' is saying search for group of eight characters a – f case insensitive, then same search but with group of four characters, three times, then group of eleven characters a-f case insensitive.

Since we would be using the $intuneScheduledTasks later to Unregister-ScheduledTask, you could get the $enrollmentId from the task path. The enrollment Id would be the first index of the scheduled task represented as a [0] index of the array, then you get the TaskPath property of the object at [0] index. We want to trim the end of the path with trailing \ character, then we split by \ and get the last index using [-1]. It looks confusing because I am chaining all the methods together, but if you output to the console one step at a time, it will make more sense. String manipulation is fun in any language, so once I got the fundamentals while practicing JavaScript, the skill was transferable to PowerShell. Trim(), Split, etc.

PowerShell String Methods

To find all the methods to use with String data type in PowerShell, you can simply type a string in a PowerShell terminal, the pipe it to Get-Member. This command get all the properties and methods associated with a PowerShell object.

"Hello World!" | Get-Member

These string methods and properties can be used is may programming languages so its beneficial to play around with these methods and understand them, especially for scripting languages that generally don’t require a lot of code.

Re-Enroll the Endpoint Without Losing Data in PowerShell

The script provided below uses a loop to remove the registry keys, and a loop to unregister the scheduled tasks associated with the Intune enrollment. It also looks for a computer certificated provided my MDM, and removes that as well. After the cleanup is complete, I invoke C:\Windows\System32\deviceenroller.exe /c /AutoEnrollMDM.

What is Deviceenroller.exe

  • C:\Windows\System32\deviceenroller.exe: This is the path to the deviceenroller.exe executable, a Windows system tool responsible for enrolling devices into management services like Microsoft Intune.
  • /c: This parameter stands for “command” and indicates that a command is being passed to deviceenroller.exe.
  • /AutoEnrollMDM: This is the specific command being passed to deviceenroller.exe. It instructs the tool to automatically enroll the device into Mobile Device Management (MDM) using the Microsoft Intune service. This will vary depending on the enrollment service.

PowerShell Script to Clean up Previous Enrollment

After running this script, to immediately register the Windows machine, you need to go to Settings > Accounts > Access work or school > Select the Entra joined account > Info > Sync. Otherwise you can wait for rediscovery between the managed workstation and Intune.

$regArr = @(
    "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\"
)

$enrollerPath = "$env:windir\system32\deviceenroller.exe"
$cert = Get-ChildItem Cert:\LocalMachine\My | ?{$_.Issuer -eq "CN=Microsoft Intune MDM Device CA"}

try{
    $enrollmentId = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Provisioning\OMADM\Logger" -Name "CurrentEnrollmentId"
}catch{
    Write-Output "Inutune Enrollment Id not found. Exit 1"; exit 1
}

Write-Output "$($Env:COMPUTERNAME) - The Intune Enrollment ID is $enrollmentId"

# unregister all tasks within the enrollment folder
$intuneScheduledTasks = Get-ScheduledTask -TaskPath "\Microsoft\Windows\EnterpriseMgmt\$enrollmentId\" -ErrorAction SilentlyContinue

if($null -eq $intuneScheduledTasks){ 
    Write-Output("Task folder {0} does not exist. Exit 1" -f "\Microsoft\Windows\EnterpriseMgmt\$enrollmentId\"); exit 1
}

foreach($task in $intuneScheduledTasks){

    Write-Output("Unregistering scheduled task - {0}" -f $task.TaskName)
    Unregister-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -Confirm:$false
}

# delete the enrollment task folder, 0 
$scheduleObj = New-Object -ComObject Schedule.Service
$scheduleObj.Connect()
$rootEnrollmentFolder = $scheduleObj.GetFolder("\Microsoft\Windows\EnterpriseMgmt")
$rootEnrollmentFolder.DeleteFolder($enrollmentId, 0)


# delete the registry keys with the enrollment ID and all sub keys
foreach($path in $regArr){

    $targetPath = Join-Path $path $enrollmentId
    if(test-path -Path $targetPath){
        Write-Output("Removing {0} and all sub-keys/items" -f $targetPath)
        Remove-Item -Path $targetPath -Recurse -Force -ErrorAction SilentlyContinue | Out-Null
    }
}

if($cert){ 
    Write-Output("{0}" -f $cert.Issuer)
    $cert | remove-item -Force -ErrorAction SilentlyContinue
}

if(test-path $enrollerPath){
    $p = Start-Process -FilePath $enrollerPath -ArgumentList @("/c", "/AutoEnrollMDM") -PassThru
    # if($p.HasExited){
    #     Write-Output("{0} - Intune Re-enrollment successfully initiated")
    # }
}

Conclusion

In summary, the provided PowerShell script exemplifies a thorough approach to addressing Intune client health issues by meticulously cleaning up previous enrollment artifacts. By removing scheduled tasks, clearing relevant registry keys, and ensuring the deletion of outdated certificates, the script paves the way for a fresh and error-free re-enrollment process. This proactive method not only resolves potential conflicts but also ensures that devices remain compliant with enterprise policies, thereby maintaining a robust and reliable Intune-managed environment. Properly managing and automating these tasks helps IT administrators sustain the integrity and efficiency of their device management practices, ultimately contributing to a more secure and well-organized infrastructure.

Leave a Reply