Src/Private/Get-AbrIntuneEnrollmentRestrictions.ps1

function Get-AbrIntuneEnrollmentRestrictions {
    <#
    .SYNOPSIS
    Documents Intune Device Enrollment Restrictions and configuration.
    .DESCRIPTION
        Collects and reports on:
          - Device Type Restrictions (platform allow/block)
          - Device Limit Restrictions (max devices per user)
          - Enrollment Status Page (ESP) profiles
          - Autopilot deployment profiles
    .NOTES
        Version: 0.1.0
        Author: Pai Wei Sing
    #>

    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory)]
        [string]$TenantId
    )

    begin {
        Write-PScriboMessage -Message "Collecting Intune Enrollment Restrictions for $TenantId."
        Show-AbrDebugExecutionTime -Start -TitleMessage 'Enrollment Restrictions'
    }

    process {
        Section -Style Heading2 'Enrollment Restrictions' {
            Paragraph "The following section documents Device Enrollment configuration for tenant $TenantId."
            BlankLine

            $TotalEnrollmentRestrictions = 0
            $TotalAutopilotProfiles      = 0
            $TotalESPProfiles            = 0

            #region Device Type Restrictions
            try {
                Write-Host " - Retrieving device type restrictions..."
                $TypeRestResp = Invoke-MgGraphRequest -Method GET `
                    -Uri "$($script:GraphEndpoint)/v1.0/deviceManagement/deviceEnrollmentConfigurations?`$expand=assignments" `
                    -ErrorAction SilentlyContinue
                $AllRestrictions = $TypeRestResp.value

                $null = ($TotalEnrollmentRestrictions = @($AllRestrictions).Count)
                if ($AllRestrictions -and @($AllRestrictions).Count -gt 0) {

                    # Device Type Restrictions
                    $TypeRestrictions = $AllRestrictions | Where-Object { $_.'@odata.type' -like '*deviceEnrollmentPlatformRestrictionsConfiguration*' }
                    if ($TypeRestrictions) {
                        Section -Style Heading3 'Device Type Restrictions' {
                            BlankLine
                            foreach ($Restriction in ($TypeRestrictions | Sort-Object priority)) {
                                $assignResolved = Resolve-IntuneAssignments -Assignments $Restriction.assignments
                                $AssignedTo = if ($assignResolved.AssignmentSummary -ne 'Not assigned') { $assignResolved.AssignmentSummary } else { 'Default (All Users)' }

                                $RestObj = [System.Collections.ArrayList]::new()
                                $restInObj = [ordered] @{
                                    'Restriction Name'     = $Restriction.displayName
                                    'Priority'             = $Restriction.priority
                                    'Assignments'          = $AssignedTo
                                }

                                # Platform-level settings
                                $Platforms = @('androidRestriction', 'androidForWorkRestriction', 'iosRestriction',
                                    'macOSRestriction', 'windowsRestriction', 'windowsMobileRestriction')
                                foreach ($PlatKey in $Platforms) {
                                    if ($Restriction.$PlatKey) {
                                        $PlatLabel = $PlatKey -replace 'Restriction', '' -replace 'androidForWork', 'Android Work Profile' `
                                            -replace 'android', 'Android' -replace 'ios', 'iOS' -replace 'macOS', 'macOS' `
                                            -replace 'windows$', 'Windows' -replace 'windowsMobile', 'Windows Mobile'
                                        $PlatData = $Restriction.$PlatKey
                                        $restInObj["$PlatLabel - Platform Blocked"]   = $PlatData.platformBlocked
                                        $restInObj["$PlatLabel - Personal Blocked"]   = $PlatData.personalDeviceEnrollmentBlocked
                                        if ($PlatData.osMinimumVersion) { $restInObj["$PlatLabel - Min OS"] = $PlatData.osMinimumVersion }
                                        if ($PlatData.osMaximumVersion) { $restInObj["$PlatLabel - Max OS"] = $PlatData.osMaximumVersion }
                                    }
                                }

                                $RestObj.Add([pscustomobject](ConvertTo-HashToYN $restInObj)) | Out-Null
                                $RestTableParams = @{ Name = "Type Restriction - $($Restriction.displayName)"; List = $true; ColumnWidths = 45, 55 }
                                $RestObj | Table @RestTableParams
                                BlankLine
                            }
                        }
                    }

                    # Device Limit Restrictions
                    $LimitRestrictions = $AllRestrictions | Where-Object { $_.'@odata.type' -like '*deviceEnrollmentLimitConfiguration*' }
                    if ($LimitRestrictions) {
                        Section -Style Heading3 'Device Limit Restrictions' {
                            BlankLine
                            $LimObj = [System.Collections.ArrayList]::new()
                            foreach ($Lim in ($LimitRestrictions | Sort-Object priority)) {
                                $assignResolved = Resolve-IntuneAssignments -Assignments $Lim.assignments
                                $AssignedTo = if ($assignResolved.AssignmentSummary -ne 'Not assigned') { $assignResolved.AssignmentSummary } else { 'Default (All Users)' }

                                $limInObj = [ordered] @{
                                    'Restriction Name'  = $Lim.displayName
                                    'Priority'          = $Lim.priority
                                    'Device Limit'      = $Lim.limit
                                    'Assignments'       = $AssignedTo
                                }
                                $LimObj.Add([pscustomobject]$limInObj) | Out-Null
                            }
                            $LimTableParams = @{ Name = "Device Limit Restrictions - $TenantId"; ColumnWidths = 35, 15, 20, 30 }
                            if ($Report.ShowTableCaptions) { $LimTableParams['Caption'] = "- $($LimTableParams.Name)" }
                            $LimObj | Table @LimTableParams
                        }
                    }

                    # Enrollment Status Page
                    $ESPProfiles = $AllRestrictions | Where-Object { $_.'@odata.type' -like '*windows10EnrollmentCompletionPageConfiguration*' }
                    $TotalESPProfiles = if ($ESPProfiles) { @($ESPProfiles).Count } else { 0 }
                    if ($ESPProfiles) {
                        Section -Style Heading3 'Enrollment Status Page (ESP)' {
                            BlankLine
                            $EspObj = [System.Collections.ArrayList]::new()
                            foreach ($ESP in ($ESPProfiles | Sort-Object priority)) {
                                $assignResolved = Resolve-IntuneAssignments -Assignments $ESP.assignments
                                $AssignedTo = if ($assignResolved.AssignmentSummary -ne 'Not assigned') { $assignResolved.AssignmentSummary } else { 'Default (All Devices)' }

                                $espInObj = [ordered] @{
                                    'ESP Profile Name'                    = $ESP.displayName
                                    'Priority'                            = $ESP.priority
                                    'Show Progress to End User'           = $ESP.showInstallationProgress
                                    'Block Device Until Provisioning'     = $ESP.blockDeviceSetupRetryByUser
                                    'Allow Reset if Installation Fails'   = $ESP.allowDeviceResetOnInstallFailure
                                    'Allow Use of Device Before Profile'  = $ESP.allowDeviceUseOnInstallFailure
                                    'Tracking Error Timeout (minutes)'    = if ($ESP.installProgressTimeoutInMinutes) { $ESP.installProgressTimeoutInMinutes } else { '--' }
                                    'Assignments'                         = $AssignedTo
                                }
                                $EspObj.Add([pscustomobject](ConvertTo-HashToYN $espInObj)) | Out-Null
                            }
                            $EspTableParams = @{ Name = "Enrollment Status Page Profiles - $TenantId"; List = $true; ColumnWidths = 50, 50 }
                            $EspObj | Table @EspTableParams
                        }
                    }

                    if (Get-IntuneBackupSectionEnabled -SectionKey 'EnrollmentRestrictions') { $script:BackupData['EnrollmentRestrictions'] = $AllRestrictions }
                    if (Get-IntuneExcelSheetEnabled -SheetKey 'EnrollmentRestrictions') {
                        $AllRestrictionsExcel = $AllRestrictions | ForEach-Object {
                            [pscustomobject]@{
                                'Name'      = $_.displayName
                                'Type'      = $_.'@odata.type' -replace '#microsoft.graph.', ''
                                'Priority'  = $_.priority
                            }
                        }
                        $script:ExcelSheets['Enrollment Restrictions'] = $AllRestrictionsExcel
                    }

                    #region InfoLevel 2 -- per-restriction Heading4 detail
                    if ($InfoLevel.EnrollmentRestrictions -ge 2) {
                        $TypeRestrictions = $AllRestrictions | Where-Object { $_.'@odata.type' -like '*deviceEnrollmentPlatformRestrictions*' } | Sort-Object priority
                        foreach ($Restriction in $TypeRestrictions) {
                            $assignResolved = Resolve-IntuneAssignments -Assignments $Restriction.assignments
                            Section -Style Heading4 $Restriction.displayName {
                                BlankLine
                                $ovObj = [System.Collections.ArrayList]::new()
                                $ovObj.Add([pscustomobject]@{ Setting = 'Restriction Name'; Value = $Restriction.displayName }) | Out-Null
                                $ovObj.Add([pscustomobject]@{ Setting = 'Priority';         Value = "$($Restriction.priority)" }) | Out-Null
                                $ovObj.Add([pscustomobject]@{ Setting = 'Included Groups';  Value = $assignResolved.IncludedGroups }) | Out-Null
                                $ovObj.Add([pscustomobject]@{ Setting = 'Excluded Groups';  Value = $assignResolved.ExcludedGroups }) | Out-Null
                                $OvParams = @{ Name = "Overview - $($Restriction.displayName)"; ColumnWidths = 30, 70 }
                                if ($Report.ShowTableCaptions) { $OvParams['Caption'] = "- $($OvParams.Name)" }
                                $ovObj | Table @OvParams

                                if ($Restriction.platformRestrictions) {
                                    BlankLine
                                    Paragraph 'Platform Settings:'
                                    BlankLine
                                    $platRows = [System.Collections.ArrayList]::new()
                                    $platMap = @{
                                        'windows'           = 'Windows'
                                        'windowsMobile'     = 'Windows Mobile'
                                        'ios'               = 'iOS / iPadOS'
                                        'android'           = 'Android'
                                        'androidForWork'    = 'Android Enterprise'
                                        'mac'               = 'macOS'
                                    }
                                    foreach ($key in $platMap.Keys) {
                                        $platData = $Restriction.platformRestrictions.$key
                                        if ($platData) {
                                            $platRows.Add([pscustomobject]([ordered]@{
                                                'Platform'         = $platMap[$key]
                                                'Platform Blocked' = if ($platData.platformBlocked)                { 'Yes' } else { 'No' }
                                                'Personal Blocked' = if ($platData.personalDeviceEnrollmentBlocked) { 'Yes' } else { 'No' }
                                                'Min OS'           = if ($platData.osMinimumVersion) { $platData.osMinimumVersion } else { '--' }
                                                'Max OS'           = if ($platData.osMaximumVersion) { $platData.osMaximumVersion } else { '--' }
                                            })) | Out-Null
                                        }
                                    }
                                    if ($platRows.Count -gt 0) {
                                        $PlatParams = @{ Name = "Platform Restrictions - $($Restriction.displayName)"; ColumnWidths = 22, 18, 18, 21, 21 }
                                        if ($Report.ShowTableCaptions) { $PlatParams['Caption'] = "- $($PlatParams.Name)" }
                                        $platRows | Table @PlatParams
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                } else {
                    Paragraph "No Enrollment Restrictions found in tenant $TenantId."
                }

            } catch {
                    if (Test-AbrGraphForbidden -ErrorRecord $_) {
                        Write-AbrPermissionError -Section 'Enrollment Restrictions' -RequiredRole 'Intune Service Administrator or Global Administrator'
                    } else {
                        Write-AbrSectionError -Section 'Enrollment Restrictions' -Message "$($_.Exception.Message)"
                    }
                }
            #endregion

            #region Windows Autopilot Deployment Profiles
            try {
                Write-Host " - Retrieving Windows Autopilot profiles..."
                # /beta required -- windowsAutopilotDeploymentProfiles is not supported in v1.0
                $AutopilotResp = Invoke-MgGraphRequest -Method GET `
                    -Uri "$($script:GraphEndpoint)/beta/deviceManagement/windowsAutopilotDeploymentProfiles?`$expand=assignments" `
                    -ErrorAction SilentlyContinue
                $AutopilotProfiles = $AutopilotResp.value

                $TotalAutopilotProfiles = if ($AutopilotProfiles) { @($AutopilotProfiles).Count } else { 0 }
                if ($TotalAutopilotProfiles -gt 0) {
                    Section -Style Heading3 'Autopilot Deployment Profiles' {
                        Paragraph "The following section documents the Windows Autopilot Deployment Profiles configured in tenant $TenantId."
                        BlankLine

                        # ── Summary table ──────────────────────────────────────────────────
                        $APObj = [System.Collections.ArrayList]::new()
                        foreach ($APProfile in ($AutopilotProfiles | Sort-Object displayName)) {
                            $assignResolved = Resolve-IntuneAssignments -Assignments $APProfile.assignments -CheckMemberCount:$script:CheckEmptyGroups
                            $AssignedTo     = $assignResolved.AssignmentSummary

                            # Determine Join Type from odata type and hybrid flag
                            $JoinType = if ($APProfile.'@odata.type' -like '*hybrid*' -or $null -ne $APProfile.hybridAzureADJoinSkipConnectivityCheck) {
                                'Microsoft Entra Hybrid Joined'
                            } else { 'Microsoft Entra Joined' }

                            # Deployment mode human-readable
                            $DeployMode = switch ($APProfile.deploymentMode) {
                                'userDriven'    { 'User-Driven' }
                                'selfDeploying' { 'Self-Deploying' }
                                default         { if ($APProfile.deploymentMode) { $APProfile.deploymentMode } else { '--' } }
                            }

                            $apInObj = [ordered] @{
                                'Profile Name'     = $APProfile.displayName
                                'Deployment Mode'  = $DeployMode
                                'Join Type'        = $JoinType
                                'User Account Type'= if ($APProfile.outOfBoxExperienceSetting.userType) {
                                                        switch ($APProfile.outOfBoxExperienceSetting.userType) {
                                                            'administrator' { 'Administrator' }
                                                            'standard'      { 'Standard' }
                                                            default         { $APProfile.outOfBoxExperienceSetting.userType }
                                                        }
                                                     } else { '--' }
                                'Device Name Template' = if ($APProfile.deviceNameTemplate) { $APProfile.deviceNameTemplate } else { 'Not configured' }
                                'Assignments'      = $AssignedTo
                                'Last Modified'    = if ($APProfile.lastModifiedDateTime) { ([datetime]$APProfile.lastModifiedDateTime).ToString('yyyy-MM-dd') } else { '--' }
                            }
                            $APObj.Add([pscustomobject]$apInObj) | Out-Null
                        }

                        $null = (& {
                            if ($HealthCheck.Intune.EnrollmentRestrictions) {
                                $null = ($APObj | Where-Object { $_.'Assignments' -eq 'Not assigned' } | Set-Style -Style Warning | Out-Null)
                            }
                        })

                        $APTableParams = @{ Name = "Autopilot Deployment Profiles - $TenantId"; ColumnWidths = 24, 14, 20, 12, 16, 7, 7 }
                        if ($Report.ShowTableCaptions) { $APTableParams['Caption'] = "- $($APTableParams.Name)" }
                        $APObj | Table @APTableParams

                        if (Get-IntuneExcelSheetEnabled -SheetKey 'AutopilotProfiles') {
                            $script:ExcelSheets['Autopilot Profiles'] = $APObj
                        }
                        if (Get-IntuneBackupSectionEnabled -SectionKey 'AutopilotProfiles') { $script:BackupData['AutopilotProfiles'] = $AutopilotProfiles }

                        # ── Per-profile detail sections (all InfoLevel) ────────────────────
                        foreach ($APProfile in ($AutopilotProfiles | Sort-Object displayName)) {
                            $assignResolved = Resolve-IntuneAssignments -Assignments $APProfile.assignments -CheckMemberCount:$script:CheckEmptyGroups
                            $OOBE = $APProfile.outOfBoxExperienceSetting

                            # Derive values
                            $JoinType = if ($APProfile.'@odata.type' -like '*hybrid*' -or $null -ne $APProfile.hybridAzureADJoinSkipConnectivityCheck) {
                                'Microsoft Entra Hybrid Joined'
                            } else { 'Microsoft Entra Joined' }

                            $DeployMode = switch ($APProfile.deploymentMode) {
                                'userDriven'    { 'User-Driven' }
                                'selfDeploying' { 'Self-Deploying' }
                                default         { if ($APProfile.deploymentMode) { $APProfile.deploymentMode } else { '--' } }
                            }

                            $UserAccountType = if ($OOBE.userType) {
                                switch ($OOBE.userType) {
                                    'administrator' { 'Administrator' }
                                    'standard'      { 'Standard' }
                                    default         { $OOBE.userType }
                                }
                            } else { '--' }

                            $HideShow = { param($boolVal) if ($boolVal) { 'Hide' } else { 'Show' } }

                            Section -Style Heading4 $APProfile.displayName {
                                BlankLine

                                # ── Overview table ──
                                $APDetailObj = [System.Collections.ArrayList]::new()
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Profile Name';                    Value = $APProfile.displayName }) | Out-Null
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Description';                     Value = if ($APProfile.description) { $APProfile.description } else { '--' } }) | Out-Null
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Assigned';                        Value = if ($assignResolved.AssignmentSummary -ne 'Not assigned') { 'Yes' } else { 'No' } }) | Out-Null
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Assignments';                     Value = $assignResolved.AssignmentSummary }) | Out-Null
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Created';                         Value = if ($APProfile.createdDateTime) { ([datetime]$APProfile.createdDateTime).ToString('yyyy-MM-dd') } else { '--' } }) | Out-Null
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Last Modified';                   Value = if ($APProfile.lastModifiedDateTime) { ([datetime]$APProfile.lastModifiedDateTime).ToString('yyyy-MM-dd') } else { '--' } }) | Out-Null
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Deployment Mode';                 Value = $DeployMode }) | Out-Null
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Join to Microsoft Entra ID as';   Value = $JoinType }) | Out-Null

                                # Hybrid-only: skip AD connectivity check
                                if ($null -ne $APProfile.hybridAzureADJoinSkipConnectivityCheck) {
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'Skip AD Connectivity Check';  Value = if ($APProfile.hybridAzureADJoinSkipConnectivityCheck) { 'Yes' } else { 'No' } }) | Out-Null
                                }

                                # Convert all targeted devices to Autopilot
                                if ($null -ne $APProfile.extractHardwareKey) {
                                    # extractHardwareKey = $true means "convert all targeted devices to Autopilot"
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'Convert All Targeted Devices to Autopilot'; Value = if ($APProfile.extractHardwareKey) { 'Yes' } else { 'No' } }) | Out-Null
                                }

                                # OOBE settings
                                if ($OOBE) {
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'Microsoft Software License Terms'; Value = (& $HideShow ($OOBE.eulaHidden)) }) | Out-Null
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'Privacy Settings';                 Value = (& $HideShow ($OOBE.privacySettingsHidden)) }) | Out-Null
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'Hide Change Account Options';      Value = (& $HideShow ($OOBE.escapeLinkHidden)) }) | Out-Null
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'User Account Type';                Value = $UserAccountType }) | Out-Null
                                }

                                # Allow pre-provisioned deployment (White Glove)
                                if ($null -ne $APProfile.enableWhiteGlove) {
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'Allow Pre-Provisioned Deployment'; Value = if ($APProfile.enableWhiteGlove) { 'Yes' } else { 'No' } }) | Out-Null
                                }

                                # Language / keyboard
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Language (Region)';                Value = if ($APProfile.language) { $APProfile.language } else { 'Operating System Default' } }) | Out-Null
                                if ($null -ne $APProfile.keyboardSelectionPageSkipped) {
                                    $APDetailObj.Add([pscustomobject]@{ Setting = 'Automatically Configure Keyboard'; Value = if ($APProfile.keyboardSelectionPageSkipped) { 'Yes' } else { 'No' } }) | Out-Null
                                }

                                # Device name template
                                $APDetailObj.Add([pscustomobject]@{ Setting = 'Apply Device Name Template';       Value = if ($APProfile.deviceNameTemplate) { $APProfile.deviceNameTemplate } else { 'Not configured' } }) | Out-Null

                                $APDetailTableParams = @{ Name = "Profile Overview - $($APProfile.displayName)"; ColumnWidths = 45, 55 }
                                if ($Report.ShowTableCaptions) { $APDetailTableParams['Caption'] = "- $($APDetailTableParams.Name)" }
                                $APDetailObj | Table @APDetailTableParams
                            }
                        }
                    }
                }
            } catch {
                    if (Test-AbrGraphForbidden -ErrorRecord $_) {
                        Write-AbrPermissionError -Section 'Autopilot Deployment Profiles' -RequiredRole 'Intune Service Administrator or Global Administrator'
                    } else {
                        Write-AbrSectionError -Section 'Autopilot Deployment Profiles' -Message "$($_.Exception.Message)"
                    }
                }
            #endregion

            #region ACSC E8 Assessment
            if ($script:IncludeACSCe8) {
                BlankLine
                Paragraph "ACSC Essential Eight Maturity Level Assessment -- Enrollment Restrictions:"
                BlankLine
                try {
                    $_v = @{
                        TotalEnrollmentRestrictions = $TotalEnrollmentRestrictions
                        TotalAutopilotProfiles      = $TotalAutopilotProfiles
                        TotalESPProfiles            = $TotalESPProfiles
                    }
                    $E8Checks = Build-AbrIntuneComplianceChecks -Definitions (Get-AbrIntuneE8Checks -Section 'EnrollmentRestrictions') -Framework E8 -CallerVariables $_v
                    New-AbrIntuneE8AssessmentTable -Checks $E8Checks -Name 'Enrollment Restrictions' -TenantId $TenantId
                    if ($E8Checks) { $null = $script:E8AllChecks.AddRange([object[]](@($E8Checks | Select-Object @{N='Section';E={'EnrollmentRestrictions'}}, ML, Control, Status, Detail))) }
                } catch { Write-AbrSectionError -Section 'E8 Enrollment Assessment' -Message "$($_.Exception.Message)" }
            }
            #endregion

            #region CIS Assessment
            if ($script:IncludeCISBaseline) {
                BlankLine
                Paragraph "CIS Microsoft 365 Foundations Benchmark Assessment -- Enrollment Restrictions:"
                BlankLine
                try {
                    $_v = @{
                        TotalEnrollmentRestrictions = $TotalEnrollmentRestrictions
                        TotalESPProfiles            = $TotalESPProfiles
                    }
                    $CISChecks = Build-AbrIntuneComplianceChecks -Definitions (Get-AbrIntuneCISChecks -Section 'EnrollmentRestrictions') -Framework CIS -CallerVariables $_v
                    New-AbrIntuneCISAssessmentTable -Checks $CISChecks -Name 'Enrollment Restrictions' -TenantId $TenantId
                    if ($CISChecks) { $null = $script:CISAllChecks.AddRange([object[]](@($CISChecks | Select-Object @{N='Section';E={'EnrollmentRestrictions'}}, CISControl, Level, Status, Detail))) }
                } catch { Write-AbrSectionError -Section 'CIS Enrollment Assessment' -Message "$($_.Exception.Message)" }
            }
            #endregion
        }
    }

    end { Show-AbrDebugExecutionTime -End -TitleMessage 'Enrollment Restrictions' }
}