SHELL/5.1.4.3.ps1

$CheckId = "5.1.4.3"
$Title = "Ensure the GA role is not added as a local administrator during Entra join"

function Get-NestedValue {
    param(
        [Parameter(Mandatory = $true)][object]$InputObject,
        [Parameter(Mandatory = $true)][string[]]$Path
    )

    $Current = $InputObject
    foreach ($Segment in $Path) {
        if ($null -eq $Current) {
            return $null
        }

        if ($Current -is [System.Collections.IDictionary]) {
            if ($Current.Contains($Segment)) {
                $Current = $Current[$Segment]
            }
            else {
                return $null
            }
        }
        else {
            $Prop = $Current.PSObject.Properties[$Segment]
            if ($null -eq $Prop) {
                return $null
            }
            $Current = $Prop.Value
        }
    }
    return $Current
}

$Uri = "https://graph.microsoft.com/beta/policies/deviceRegistrationPolicy"

try {
    $Policy = Invoke-MgGraphRequest -Method GET -Uri $Uri
    $EnableGlobalAdmins = Get-NestedValue -InputObject $Policy -Path @("azureADJoin", "localAdmins", "enableGlobalAdmins")

    if ($null -eq $EnableGlobalAdmins) {
        [pscustomobject]@{
            CheckId   = $CheckId
            Title     = $Title
            Status    = "MANUAL_REVIEW"
            Pass      = $null
            Evidence  = [pscustomobject]@{
                Uri             = $Uri
                enableGlobalAdmins = $null
                ReviewAction    = "Verify enableGlobalAdmins is False."
            }
            Error     = "Could not determine azureADJoin.localAdmins.enableGlobalAdmins."
            Timestamp = Get-Date
        }
    }
    else {
        $EnableGlobalAdminsBool = [bool]$EnableGlobalAdmins
        $Pass = -not $EnableGlobalAdminsBool

        [pscustomobject]@{
            CheckId   = $CheckId
            Title     = $Title
            Status    = if ($Pass) { "PASS" } else { "FAIL" }
            Pass      = $Pass
            Evidence  = [pscustomobject]@{
                Uri                  = $Uri
                enableGlobalAdmins   = $EnableGlobalAdminsBool
                RecommendedState     = "False"
            }
            Error     = $null
            Timestamp = Get-Date
        }
    }
}
catch {
    $Message = $_.Exception.Message
    $IsPermissionIssue = $Message -match "(?i)forbidden|insufficient|authorization|access denied"

    [pscustomobject]@{
        CheckId   = $CheckId
        Title     = $Title
        Status    = if ($IsPermissionIssue) { "MANUAL_REVIEW" } else { "ERROR" }
        Pass      = $null
        Evidence  = [pscustomobject]@{
            Uri                   = $Uri
            RequiredGraphScope    = "Policy.Read.DeviceConfiguration"
            ReviewAction          = "Verify enableGlobalAdmins is False."
        }
        Error     = $Message
        Timestamp = Get-Date
    }
}