SHELL/4.1.ps1

$CheckId = "4.1"
$Title = "Ensure devices without a compliance policy are marked 'not compliant'"

$Uri = "https://graph.microsoft.com/v1.0/deviceManagement/settings"

try {
    $Settings = Invoke-MgGraphRequest -Method GET -Uri $Uri
    $SecureByDefault = $Settings.secureByDefault

    if ($null -eq $SecureByDefault) {
        [pscustomobject]@{
            CheckId   = $CheckId
            Title     = $Title
            Status    = "MANUAL_REVIEW"
            Pass      = $null
            Evidence  = [pscustomobject]@{
                Uri                  = $Uri
                secureByDefault      = $null
                ReviewAction         = "Verify the Intune setting 'Mark devices with no compliance policy assigned as' is set to Not compliant."
            }
            Error     = "secureByDefault was not returned by the endpoint."
            Timestamp = Get-Date
        }
    }
    else {
        $SecureByDefaultBool = [bool]$SecureByDefault
        [pscustomobject]@{
            CheckId   = $CheckId
            Title     = $Title
            Status    = if ($SecureByDefaultBool) { "PASS" } else { "FAIL" }
            Pass      = $SecureByDefaultBool
            Evidence  = [pscustomobject]@{
                Uri                  = $Uri
                secureByDefault      = $SecureByDefaultBool
                RecommendedState     = "True"
            }
            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    = "DeviceManagementConfiguration.Read.All"
            ReviewAction          = "Verify secureByDefault is True."
        }
        Error     = $Message
        Timestamp = Get-Date
    }
}