PSReEnrollment.psm1

Function Invoke-IntuneReEnrollment
{
      [CmdletBinding(
            SupportsShouldProcess=$True,
            ConfirmImpact="High")]
      Param
      (
            [Switch]$ReportOnly
      )

      $User = [Security.Principal.WindowsIdentity]::GetCurrent()
      $Role = (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
      
      if(!$Role)
      {
            Write-Warning "Run with administrator privileges!"    
      } 

      $EnrollmentsPath = "HKLM:\SOFTWARE\Microsoft\Enrollments\"
      $Enrollments = Get-ChildItem -Path $EnrollmentsPath
      Foreach ($Enrollment in $Enrollments)
      {
            $EnrollmentObject = Get-ItemProperty Registry::$Enrollment
            if ($EnrollmentObject."DiscoveryServiceFullURL" -eq "https://enrollment.manage.microsoft.com/enrollmentserver/discovery.svc") 
            {
                  $EnrollmentPath = $EnrollmentsPath + $EnrollmentObject."PSChildName"
                  $EnrollmentPath 

                  if($ReportOnly -ne $true)
                  {
                        if($null -ne $EnrollmentPath)
                        {
                              If ($pscmdlet.ShouldProcess($Env:COMPUTERNAME,"Are you sure you want to clear your local Intune ID?")) 
                              {
                                    reg export $($EnrollmentPath.Replace(":","")) $($ENV:ProgramData+"\EnrollmentPath.reg") /y
                                    Remove-Item -Path $EnrollmentPath -Recurse
                                    C:\Windows\System32\deviceenroller.exe /c /AutoEnrollMDM
                              }
                        }
                  }
            }
      }
}

Function Test-IntuneReEnrollment 
{
      [CmdletBinding()]
      Param
      (
            [Switch]$Details
      )

      $WinEvent = Get-WinEvent -FilterHashtable @{LogName="Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin";ID=209} -MaxEvents 1

      if($Details)
      {
            $WinEvent | Format-List
      }

      if($WinEvent | Where-Object Message -Match "0x80072f0c")
      {
            Write-Host "Connectivity unknown error (0x80072f0c) exist!" -ForegroundColor Red
            Return $true
      } else {
            Return $false
      }
}


Get-ChildItem -Path $PSScriptRoot | Unblock-File
New-Alias -Name "InvReEnr" Invoke-IntuneReEnrollment
New-Alias -Name "TstReEnr" Test-IntuneReEnrollment

Export-ModuleMember -Cmdlet * -Alias * -Function *