Repair-ADSyncDiagsAutoUpgradeState.ps1

Function Repair-ADSyncDiagsAutoUpgradeState
{
    # Checking UpdateCheckEnabled Registry key
    $regkey = "HKLM:\SOFTWARE\Microsoft\ADHealthAgent\Sync"
    $name = "UpdateCheckEnabled"
    Try
    {
        $val = Get-ItemProperty -Path $regkey -Name $name -ErrorAction Stop
        Write-Host 'UpdateCheckEnabled: ' $val.UpdateCheckEnabled
    }
    Catch [System.Security.SecurityException]
    {
        Write-Error "Please execute this script in Windows PowerShell with 'Run As Administrator': $($_.Exception.Message)"
        Return
    }

    # Checking ADSync AutoUpgrade Status
    Try
    {
        $autoUpgradeState = Get-ADSyncAutoUpgrade -ErrorAction Stop
        Write-Host 'ADSyncAutoUpgrade: ' $autoUpgradeState
    }
    Catch
    {
        Write-Error "Error retrieving ADSync AutoUpgrade status: $($_.Exception.Message)"
        Return
    }    

    # Checking AutoUpgrade State
    $isAgentDisabled = $val.UpdateCheckEnabled -eq 0
    $isAutoUpgradeAllowed = $autoUpgradeState -ne 'disabled'
    If($isAutoUpgradeAllowed -and $isAgentDisabled -or 1 -eq 1)
    {
        # Applying AutoUpgrade fix
        Write-Host "Fixing AutoUpgrade status and restarting AutoUpgrade service..."
        Set-ItemProperty -path $regkey -name $name -value 1
        Restart-Service "AzureADConnectHealthSyncMonitor"
        Write-Host "Result: AutoUpgrade fix has been applied successfully." 
    }
    Else
    {
        # Skipping AutoUpgrade fix
        Write-Host "Result: AutoUpgrade fix is not required."
    }
}

Repair-ADSyncDiagsAutoUpgradeState