New-GSADomainControllerApp.ps1

<#PSScriptInfo

.VERSION 1.1

.GUID c427f7b9-719f-41d2-a415-5d5a59bda183

.AUTHOR Richard Hicks

.COMPANYNAME Richard M. Hicks Consulting, Inc.

.COPYRIGHT Copyright (C) 2026 Richard M. Hicks Consulting, Inc. All Rights Reserved.

.LICENSE Licensed under the MIT License. See LICENSE file in the project root for full license information.

.LICENSEURI https://github.com/richardhicks/gsa/blob/main/LICENSE

.PROJECTURI https://github.com/richardhicks/gsa/blob/main/New-GSADomainControllerApp.ps1

.TAGS Entra, PrivateAccess, GlobalSecureAccess, GSA, ZTNA, ZeroTrust, Kerberos, SSO, ActiveDirectory, DomainController, DeviceAccess, MicrosoftGraph

.EXTERNALMODULEDEPENDENCIES ActiveDirectory

.RELEASENOTES
    1.1 - Binds new applications to the default connector group unless -ConnectorGroupName is specified. Binds connector groups with no active connectors, with a warning. Removes -SkipConnectorCheck. Adds -EnableDeviceAccess. Fixes an error that stopped the script while hiding new applications from users.
    1.0 - Initial release.

#>


<#

.SYNOPSIS
    Creates a hidden, unassigned Global Secure Access (Microsoft Entra Private Access) enterprise application that publishes Active Directory domain controllers to support Kerberos SSO.

.DESCRIPTION
    This script builds the domain controller publishing described in Microsoft's guidance for Kerberos SSO with Private Access. It creates a Global Secure Access enterprise application, binds it to a private network connector group, and adds application segments for each domain controller.

    For each domain controller, the script publishes its FQDN and the IPv4 address reported by Active Directory. Each destination gets one TCP segment and one UDP segment carrying the ports Microsoft lists for domain controllers:

    - TCP: 88, 135, 389, 445, 464, 636, 3268, 3269, 49152-65535
    - UDP: 88, 123, 135, 389, 445, 464, 49152-65535

    GSA does not support IPv6, so IPv6 addresses are never published.

    The application is an infrastructure service, so the script hides it from users (My Apps and the Microsoft 365 app launcher) and requires assignment. The script does not assign any users or groups. Review the application in the Entra admin center and assign synchronized users or groups when approved.

    By default, the application is bound to the default connector group, even if the group has no active connectors. The script finds the default group by its isDefault property, so it is found even if it was renamed. If the default group has no active connectors, the script warns that the application must be reassigned to the connector group for the domain controllers' AD site when that group is ready. If the default group has active connectors, the summary notes that best practice is to use the default group only for staging. Use -ConnectorGroupName to bind the application to another group instead.

    Use -EnableDeviceAccess to turn on 'Enable Device Access with Global Secure Access' for the application. Device Access lets Microsoft Entra joined and hybrid joined Windows devices reach the domain controllers before a user signs in. After the script runs, add the application to a Device Access profile and assign the profile to devices. Device Access is in preview.

    Microsoft recommends publishing only the domain controllers in the Active Directory site where the Private Access connectors are installed. By default, you supply those domain controllers with -DomainController. Use -AllDomainControllers to publish every domain controller in the forest instead.

    If an application with the same name exists, the script stops unless -UpdateExisting is specified. With -UpdateExisting, the script adds missing segments, reports segments that differ or are not part of this run, and never deletes anything. It never moves the application to another connector group, and it keeps an administrator's changes to the hidden and assignment required settings unless -ResetAppSettings is specified. Rerun with -UpdateExisting to finish an application after a partial failure.

.PARAMETER DomainController
    One or more domain controllers to publish, by short name or FQDN. Each name is looked up in every domain in the forest. The script stops before making changes if any name is not a domain controller, matches more than one domain controller, or has no IPv4 address in Active Directory.

.PARAMETER AllDomainControllers
    Publishes every domain controller in every domain of the forest instead of a supplied list. Intended for single-site environments, or for administrators who will delete segments for domain controllers outside the connectors' AD site before assigning the application.

.PARAMETER ConnectorGroupName
    The name of the private network connector group to bind to a new application. Optional. If omitted, the application is bound to the default connector group, found by its isDefault property. The application is bound to the group even if it has no active connectors, with a warning. This lets you stage the application before connectors are installed.

    With -UpdateExisting, this parameter is ignored and the application stays in its current connector group. The only exception is an existing application with no connector group, such as one left by a run that stopped early, which is bound to this group, or to the default connector group if this parameter is omitted.

.PARAMETER ApplicationName
    The display name of the enterprise application. The default is 'Enterprise Domain Controllers'.

.PARAMETER TenantId
    The tenant ID (GUID) or a verified domain name of the Microsoft Entra tenant. Optional. If omitted, the script uses the tenant of the account you sign in with.

.PARAMETER UpdateExisting
    Updates an existing application with the same name instead of stopping. Adds missing segments, re-applies the Private Access setting, and reports segments that differ or are not part of this run. Nothing is deleted, and Device Access is never turned off.

    The connector group is never changed. If 'Visible to users' or 'Assignment required' differ from the defaults this script sets, a warning is shown and the settings are left as they are. Use -ResetAppSettings to restore them.

.PARAMETER ResetAppSettings
    With -UpdateExisting, hides the application from users and requires assignment again, undoing changes made in the Entra admin center. New applications always get these settings, so this switch only affects existing applications.

.PARAMETER EnableDeviceAccess
    Turns on 'Enable Device Access with Global Secure Access' for the application, so Microsoft Entra joined and hybrid joined Windows devices can reach the domain controllers before a user signs in. Works with new applications and, with -UpdateExisting, existing ones. The script reads the setting back to confirm it was applied. If it can't be enabled, the script warns, still adds the segments, and exits with code 1.

    Device Access also requires a Device Access profile that includes the application and is assigned to devices. The script does not create the profile. Device Access is in preview.

.INPUTS
    None.

.OUTPUTS
    System.Management.Automation.PSCustomObject

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc1, dc2

    Creates the 'Enterprise Domain Controllers' application, binds it to the default connector group, and publishes dc1 and dc2.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc1, dc2 -ConnectorGroupName 'HQ Connectors'

    Creates the 'Enterprise Domain Controllers' application, binds it to the 'HQ Connectors' connector group, and publishes dc1 and dc2.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc1, dc2 -EnableDeviceAccess

    Creates the application in the default connector group, publishes dc1 and dc2, and enables Device Access so devices can reach the domain controllers before a user signs in.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc1, dc2 -UpdateExisting -EnableDeviceAccess

    Enables Device Access on the existing application and adds any missing segments for dc1 and dc2.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc1.corp.example.com, dc2.corp.example.com -WhatIf

    Validates the domain controllers and finds the default connector group, and shows the application and segments that would be created, without making changes.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -AllDomainControllers

    Publishes every domain controller in the forest to an application bound to the default connector group. Delete segments for domain controllers outside the connectors' AD site before assigning the application.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc3 -UpdateExisting

    Adds dc3 to the existing 'Enterprise Domain Controllers' application. The connector group and the hidden and assignment required settings are not changed.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc1, dc2 -UpdateExisting -ResetAppSettings

    Adds any missing segments for dc1 and dc2, and hides the existing application from users and requires assignment again.

.EXAMPLE
    .\New-GSADomainControllerApp.ps1 -DomainController dc5, dc6 -ConnectorGroupName 'Branch Connectors' -ApplicationName 'Enterprise Domain Controllers - Branch'

    Creates a separate application for the domain controllers in another site, bound to that site's connector group.

.LINK
    https://learn.microsoft.com/en-us/entra/global-secure-access/how-to-configure-kerberos-sso#publish-domain-controllers

.LINK
    https://learn.microsoft.com/en-us/graph/tutorial-entra-private-access

.LINK
    https://learn.microsoft.com/en-us/entra/global-secure-access/how-to-create-device-access-profile

.NOTES
    Version: 1.1
    Creation Date: November 25, 2026
    Last Updated: December 1, 2026
    Author: Richard Hicks
    Organization: Richard M. Hicks Consulting, Inc.
    Contact: rich@richardhicks.com
    Website: https://www.richardhicks.com/

    Requirements:
    - The ActiveDirectory module (RSAT) and the Microsoft.Graph.Authentication module.
    - An account with the Application Administrator and Global Secure Access Administrator roles.
    - Delegated Microsoft Graph permissions: Application.ReadWrite.All, Directory.ReadWrite.All (connector groups), and NetworkAccess.Read.All (forwarding profile check).
    - An active private network connector in the application's connector group before clients can reach the domain controllers. The application can be created before connectors are installed.
    - For -EnableDeviceAccess: Microsoft Entra joined or hybrid joined Windows devices with a Global Secure Access client that supports Device Access. Domain-joined-only devices aren't supported.

    This script uses the Microsoft Graph beta endpoint, which can change without notice.

#>


#Requires -Version 5.1
#Requires -Modules ActiveDirectory
#Requires -Modules @{ ModuleName = 'Microsoft.Graph.Authentication'; ModuleVersion = '2.0.0' }

[CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Specified')]

Param (

    [Parameter(Mandatory, ParameterSetName = 'Specified', HelpMessage = 'Enter the domain controllers in the connectors'' AD site.')]
    [ValidatePattern('^[A-Za-z0-9][A-Za-z0-9.-]*$')]
    [string[]]$DomainController,
    [Parameter(Mandatory, ParameterSetName = 'All')]
    [switch]$AllDomainControllers,
    [ValidateNotNullOrEmpty()]
    [string]$ConnectorGroupName,
    [ValidateNotNullOrEmpty()]
    [string]$ApplicationName = 'Enterprise Domain Controllers',
    [string]$TenantId,
    [switch]$UpdateExisting,
    [switch]$ResetAppSettings,
    [switch]$EnableDeviceAccess

)

#Region Logging

# Start transcript, including -WhatIf runs
$LogPath = Join-Path -Path $env:ProgramData -ChildPath 'RMHCI\PowerShell'
$LogFile = Join-Path -Path $LogPath -ChildPath "New-GSADomainControllerApp_$(Get-Date -Format 'yyyyMMdd-HHmmss').log"

If (-not (Test-Path -Path $LogPath)) {

    New-Item -Path $LogPath -ItemType Directory -Force -WhatIf:$false -Confirm:$false | Out-Null

}

Start-Transcript -Path $LogFile -WhatIf:$false -Confirm:$false | Out-Null
$ExitCode = 0

#EndRegion

#Region Functions

# Retry Graph requests that fail while a newly created object replicates across Entra ID
# Throttling (429) and service errors (503, 504) are retried by the Microsoft Graph SDK itself
Function Invoke-GraphRequestWithRetry {

    [CmdletBinding()]

    Param (

        [Parameter(Mandatory)]
        [hashtable]$Request,
        [int]$MaxAttempts = 6,
        [int]$DelaySeconds = 10

    )

    For ($Attempt = 1; $Attempt -le $MaxAttempts; $Attempt++) {

        Try {

            Return Invoke-MgGraphRequest @Request -ErrorAction Stop

        }

        Catch {

            $StatusCode = $null

            If ($_.Exception.Response) { $StatusCode = [int]$_.Exception.Response.StatusCode }

            $ErrorText = "$($_.ErrorDetails.Message) $($_.Exception.Message)"
            $IsReplicationDelay = ($StatusCode -eq 404) -or
                ($StatusCode -eq 400 -and $ErrorText -match 'not ?found|does ?not ?exist|does not reference a valid')

            If (-not $IsReplicationDelay -or $Attempt -eq $MaxAttempts) { Throw }
            Write-Verbose "Request failed with status $StatusCode (attempt $Attempt of $MaxAttempts). Retrying in $DelaySeconds seconds..."
            Start-Sleep -Seconds $DelaySeconds

        }

    }

}

# Return every item from a Graph collection, following @odata.nextLink
Function Get-GraphCollection {

    [CmdletBinding()]

    Param (

        [Parameter(Mandatory)]
        [string]$Uri

    )

    $NextUri = $Uri

    While ($NextUri) {

        $Response = Invoke-MgGraphRequest -Method GET -Uri $NextUri -ErrorAction Stop

        ForEach ($Item in $Response.value) { $Item }

        $NextUri = $Response.'@odata.nextLink'

    }

}

# Return the message from a Graph error, or the exception message
Function Get-GraphErrorMessage {

    [CmdletBinding()]

    [OutputType([string])]

    Param (

        [Parameter(Mandatory)]
        [System.Management.Automation.ErrorRecord]$ErrorRecord

    )

    # Invoke-MgGraphRequest puts the request line and headers ahead of the JSON body, so extract the JSON first
    $Details = "$($ErrorRecord.ErrorDetails.Message)"
    $JsonStart = $Details.IndexOf('{"error"')

    If ($JsonStart -ge 0) {

        Try {

            $GraphError = ($Details.Substring($JsonStart).Trim().TrimEnd('"') | ConvertFrom-Json -ErrorAction Stop).error

            If ($GraphError.message) { Return "$($GraphError.code): $($GraphError.message)" }

        }

        Catch {

            Write-Verbose 'The Graph error body could not be parsed.'

        }

    }

    Return $ErrorRecord.Exception.Message

}

# Find a connector group by name, or the default connector group, and check for an active connector
Function Resolve-ConnectorGroup {

    [CmdletBinding(DefaultParameterSetName = 'Name')]

    Param (

        [Parameter(Mandatory, ParameterSetName = 'Name')]
        [string]$Name,
        [Parameter(Mandatory, ParameterSetName = 'Default')]
        [switch]$Default,
        [Parameter(Mandatory)]
        [string]$GraphBaseUri

    )

    $AllGroups = @(Get-GraphCollection -Uri "$GraphBaseUri/onPremisesPublishingProfiles/applicationProxy/connectorGroups")

    If ($Default) {

        # Match on the isDefault property, so a renamed default group is still found
        $Groups = @($AllGroups | Where-Object { $_.isDefault -eq $true })

        If ($Groups.Count -eq 0) { Throw 'The default connector group was not found. Use -ConnectorGroupName to specify a connector group. No changes were made.' }
        If ($Groups.Count -gt 1) { Throw 'More than one connector group is marked as the default. Use -ConnectorGroupName to specify a connector group. No changes were made.' }

        Write-Verbose "Found the default connector group '$($Groups[0].name)'."

    }

    Else {

        $Groups = @($AllGroups | Where-Object { $_.name -eq $Name })

        If ($Groups.Count -eq 0) { Throw "Connector group '$Name' was not found. No changes were made." }
        If ($Groups.Count -gt 1) { Throw "More than one connector group is named '$Name'. Rename one of them and run the script again. No changes were made." }

    }

    $Group = $Groups[0]
    $Connectors = @(Get-GraphCollection -Uri "$GraphBaseUri/onPremisesPublishingProfiles/applicationProxy/connectorGroups/$($Group.id)/members")
    $ActiveConnectors = @($Connectors | Where-Object { $_.status -eq 'active' })
    $Group['activeConnectorCount'] = $ActiveConnectors.Count

    # Any group is used even with no active connectors. The summary reports it for the default group
    If ($ActiveConnectors.Count -eq 0 -and -not $Default) {

        Write-Warning "Connector group '$($Group.name)' has no active connectors ($($Connectors.Count) connector(s) in the group). Clients can't reach the domain controllers until the group has an active connector."

    }

    Write-Verbose "Connector group '$($Group.name)' ($($Group.id)) has $($ActiveConnectors.Count) active connector(s)."
    Return $Group

}

# Expand single ports to the 'port-port' form Graph uses
Function ConvertTo-PortRange {

    [CmdletBinding()]

    [OutputType([string])]

    Param (

        [Parameter(Mandatory)]
        [string[]]$Port

    )

    ForEach ($Item in $Port) {

        If ($Item -match '-') { $Item } Else { "$Item-$Item" }

    }

}

# Normalize a port list for comparison
Function Get-PortKey {

    [CmdletBinding()]

    Param (

        [string[]]$Port

    )

    (@($Port) | ForEach-Object { "$_".Trim() } | Sort-Object) -join ','

}

# Convert a domain controller object to the properties the script uses
Function ConvertTo-DcRecord {

    [CmdletBinding()]

    Param (

        [Parameter(Mandatory)]
        $InputObject

    )

    [PSCustomObject]@{

        Name        = $InputObject.Name
        HostName    = $InputObject.HostName.ToLower()
        IPv4Address = $InputObject.IPv4Address
        Site        = $InputObject.Site
        Domain      = $InputObject.Domain

    }

}

# Return $true when the value is a valid IPv4 address
Function Test-IPv4Address {

    [CmdletBinding()]

    [OutputType([bool])]

    Param (

        [string]$Address

    )

    $Parsed = $null
    Return ([System.Net.IPAddress]::TryParse($Address, [ref]$Parsed) -and $Parsed.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork)

}

#EndRegion

Try {

    $GraphBeta = 'https://graph.microsoft.com/beta'
    $CustomAppTemplateId = '8adf8e6e-67b2-4cf2-a259-e3dc5476c621'

    # Ports from Microsoft's Kerberos SSO guidance for domain controllers
    $PortMap = [ordered]@{

        tcp = @(ConvertTo-PortRange -Port '88', '135', '389', '445', '464', '636', '3268', '3269', '49152-65535')
        udp = @(ConvertTo-PortRange -Port '88', '123', '135', '389', '445', '464', '49152-65535')

    }

    #Region Domain controllers

    # Collect the domain controllers before connecting to Graph, so bad input fails fast
    Write-Verbose 'Reading the Active Directory forest...'
    $ForestDomains = @((Get-ADForest -ErrorAction Stop).Domains)
    $DcList = [ordered]@{}

    If ($AllDomainControllers) {

        Write-Warning 'Microsoft recommends publishing only the domain controllers in the AD site where the Private Access connectors are installed. Every domain controller in the forest will be published. Delete segments for domain controllers in other sites before assigning the application.'

        ForEach ($Domain in $ForestDomains) {

            Try {

                $DomainDcs = @(Get-ADDomainController -Filter * -Server $Domain -ErrorAction Stop)

            }

            Catch {

                Write-Warning "Unable to read domain controllers from domain '$Domain'. Its domain controllers are skipped. $($_.Exception.Message)"
                Continue

            }

            ForEach ($Dc in $DomainDcs) {

                If (-not (Test-IPv4Address -Address $Dc.IPv4Address)) {

                    Write-Warning "Domain controller '$($Dc.HostName)' has no IPv4 address in Active Directory and is skipped."
                    Continue

                }

                $Record = ConvertTo-DcRecord -InputObject $Dc
                $DcList[$Record.HostName] = $Record

            }

        }

    }

    Else {

        $Problems = [System.Collections.Generic.List[string]]::new()
        $UnreachableDomains = [System.Collections.Generic.List[string]]::new()

        ForEach ($Name in $DomainController) {

            $Name = $Name.Trim().TrimEnd('.').ToLower()

            # FQDNs match on host name, short names match on the DC name
            $Filter = If ($Name.Contains('.')) { "HostName -eq '$Name'" } Else { "Name -eq '$Name'" }
            $Found = @()

            ForEach ($Domain in $ForestDomains) {

                If ($UnreachableDomains -contains $Domain) { Continue }

                Try {

                    $Found += @(Get-ADDomainController -Filter $Filter -Server $Domain -ErrorAction Stop)

                }

                Catch {

                    Write-Warning "Unable to search domain '$Domain'. It is skipped for the remaining lookups. $($_.Exception.Message)"
                    $UnreachableDomains.Add($Domain)

                }

            }

            If ($Found.Count -eq 0) {

                $Message = "'$Name' is not a domain controller in this forest."

                If ($UnreachableDomains.Count -gt 0) { $Message += " Domains that could not be searched: $($UnreachableDomains -join ', ')." }

                $Problems.Add($Message)
                Continue

            }

            If ($Found.Count -gt 1) {

                $Problems.Add("'$Name' matches more than one domain controller ($(($Found.HostName) -join ', ')). Specify the FQDN.")
                Continue

            }

            If (-not (Test-IPv4Address -Address $Found[0].IPv4Address)) {

                $Problems.Add("'$($Found[0].HostName)' has no IPv4 address in Active Directory.")
                Continue

            }

            $Record = ConvertTo-DcRecord -InputObject $Found[0]
            $DcList[$Record.HostName] = $Record

        }

        If ($Problems.Count -gt 0) {

            Throw "No changes were made. Fix these domain controller entries and run the script again:`n - $($Problems -join "`n - ")"

        }

    }

    If ($DcList.Count -eq 0) { Throw 'No domain controllers with an IPv4 address were found. No changes were made.' }

    # Process and report domain controllers in host name order. Numbers are padded so dc2 sorts before dc10
    $SortedDcs = [ordered]@{}
    $NaturalOrder = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(10, '0') }) }

    ForEach ($Key in ($DcList.Keys | Sort-Object -Property $NaturalOrder)) { $SortedDcs[$Key] = $DcList[$Key] }

    $DcList = $SortedDcs

    Write-Verbose "Domain controllers to publish: $($DcList.Keys -join ', ')."

    #EndRegion

    #Region Connect

    # Directory.ReadWrite.All is the least privileged delegated permission for connector groups
    $RequiredScopes = 'Application.ReadWrite.All', 'Directory.ReadWrite.All', 'NetworkAccess.Read.All'

    $ConnectParams = @{

        Scopes      = $RequiredScopes
        NoWelcome   = $true
        ErrorAction = 'Stop'

    }

    If ($TenantId) { $ConnectParams['TenantId'] = $TenantId }

    Write-Verbose 'Connecting to Microsoft Graph...'
    Connect-MgGraph @ConnectParams
    $Context = Get-MgContext

    # Confirm the permissions were granted before making changes
    $MissingScopes = @($RequiredScopes | Where-Object { $Context.Scopes -notcontains $_ })

    If ($MissingScopes.Count -gt 0) {

        Throw "The Graph session is missing these delegated permissions: $($MissingScopes -join ', '). Run Disconnect-MgGraph, then run the script again and consent to the permissions."

    }

    Try {

        $TenantName = (Invoke-MgGraphRequest -Method GET -Uri "$GraphBeta/organization?`$select=displayName" -ErrorAction Stop).value[0].displayName

    }

    Catch {

        $TenantName = 'Unknown'

    }

    Write-Information "Connected to tenant '$TenantName' ($($Context.TenantId)) as $($Context.Account)." -InformationAction Continue

    #EndRegion

    #Region Prerequisites

    # The Private Access forwarding profile must be enabled for clients to use the application
    Try {

        $ProfileFilter = [uri]::EscapeDataString("trafficForwardingType eq 'private'")
        $PrivateProfile = @(Get-GraphCollection -Uri "$GraphBeta/networkAccess/forwardingProfiles?`$filter=$ProfileFilter") | Select-Object -First 1

        If (-not $PrivateProfile) {

            Write-Warning 'The Private Access forwarding profile was not found. Confirm Global Secure Access is activated for this tenant.'

        }

        ElseIf ($PrivateProfile.state -ne 'enabled') {

            Write-Warning "The Private Access forwarding profile is '$($PrivateProfile.state)'. Clients can't reach the domain controllers until it is enabled (Global Secure Access > Connect > Traffic forwarding)."

        }

        Else {

            Write-Verbose 'The Private Access forwarding profile is enabled.'

        }

    }

    Catch {

        Write-Warning "Unable to check the Private Access forwarding profile. $(Get-GraphErrorMessage -ErrorRecord $_)"

    }

    #EndRegion

    #Region Application

    $AppFilter = [uri]::EscapeDataString("displayName eq '$($ApplicationName -replace "'", "''")'")
    $ExistingApps = @(Get-GraphCollection -Uri "$GraphBeta/applications?`$filter=$AppFilter&`$select=id,appId,displayName")

    If ($ExistingApps.Count -gt 1) { Throw "More than one application is named '$ApplicationName'. No changes were made." }

    If ($ExistingApps.Count -eq 1 -and -not $UpdateExisting) {

        Throw "An application named '$ApplicationName' already exists. Use -UpdateExisting to add missing segments to it, or -ApplicationName to create a different application. No changes were made."

    }

    $IsNewApp = $ExistingApps.Count -eq 0
    $AppObjectId = $null
    $SpObjectId = $null
    $AppCreated = $false
    $AppSettingsApplied = $false
    $NeedsPublishing = $true
    $ConnectorGroup = $null
    $BoundGroupName = '(none)'
    $BoundGroupIsDefault = $false
    $BoundActiveConnectors = $null
    $DeviceAccessEnabled = $false
    $DeviceAccessStatus = 'Not enabled'

    # Without -ConnectorGroupName, use the default connector group, even if it has no active connectors
    $GroupParams = @{ GraphBaseUri = $GraphBeta }

    If ($ConnectorGroupName) { $GroupParams['Name'] = $ConnectorGroupName } Else { $GroupParams['Default'] = $true }

    # A new application needs a connector group. Resolve it before making any changes
    If ($IsNewApp) {

        $ConnectorGroup = Resolve-ConnectorGroup @GroupParams

    }

    If (-not $IsNewApp) {

        $AppObjectId = $ExistingApps[0].id
        Write-Verbose "Using existing application '$ApplicationName' ($AppObjectId)."

        # Never convert an application that is published some other way, such as a Quick Access or web app
        $Publishing = (Invoke-MgGraphRequest -Method GET -Uri "$GraphBeta/applications/$($AppObjectId)?`$select=onPremisesPublishing" -ErrorAction Stop).onPremisesPublishing

        If ($Publishing.applicationType -and $Publishing.applicationType -ne 'nonwebapp') {

            Throw "The existing application '$ApplicationName' has application type '$($Publishing.applicationType)', not a Global Secure Access enterprise app. No changes were made."

        }

        $NeedsPublishing = -not ($Publishing.applicationType -eq 'nonwebapp' -and $Publishing.isAccessibleViaZTNAClient)

        # Device Access is never turned off. An application that already has it is reported as enabled
        If ($Publishing.isDeviceAccessEnabled -eq $true) {

            $DeviceAccessEnabled = $true
            $DeviceAccessStatus = 'Enabled'

        }

        # Never move an existing application to another connector group. A missing connector group returns 404
        Try {

            $CurrentGroup = Invoke-MgGraphRequest -Method GET -Uri "$GraphBeta/applications/$AppObjectId/connectorGroup" -ErrorAction Stop

        }

        Catch {

            $CurrentGroup = $null

        }

        If ($CurrentGroup.id) {

            $BoundGroupName = If ($CurrentGroup.name) { $CurrentGroup.name } Else { $CurrentGroup.id }
            $BoundGroupIsDefault = $CurrentGroup.isDefault -eq $true

            # Count active connectors in the default group for the summary
            If ($BoundGroupIsDefault) {

                Try {

                    $BoundActiveConnectors = @(Get-GraphCollection -Uri "$GraphBeta/onPremisesPublishingProfiles/applicationProxy/connectorGroups/$($CurrentGroup.id)/members" | Where-Object { $_.status -eq 'active' }).Count

                }

                Catch {

                    Write-Warning "Unable to read the connectors in the default connector group. $(Get-GraphErrorMessage -ErrorRecord $_)"

                }

            }

            If ($ConnectorGroupName -and $ConnectorGroupName -ne $BoundGroupName) {

                Write-Warning "-ConnectorGroupName is ignored with -UpdateExisting. The application stays bound to connector group '$BoundGroupName'. Change the connector group in the Entra admin center if needed."

            }

        }

        # An earlier run may have stopped before binding a connector group. Binding one is not a move
        Else {

            $ConnectorGroup = Resolve-ConnectorGroup @GroupParams
            Write-Warning "The application has no connector group. It will be bound to '$($ConnectorGroup.name)'."

        }

        $SpFilter = [uri]::EscapeDataString("appId eq '$($ExistingApps[0].appId)'")
        $SpObjectId = (@(Get-GraphCollection -Uri "$GraphBeta/servicePrincipals?`$filter=$SpFilter&`$select=id") | Select-Object -First 1).id

        If (-not $SpObjectId) { Throw "The existing application '$ApplicationName' has no service principal (enterprise application)." }

    }

    ElseIf ($PSCmdlet.ShouldProcess($ApplicationName, 'Create Global Secure Access enterprise application')) {

        $InstantiateRequest = @{

            Method      = 'POST'
            Uri         = "$GraphBeta/applicationTemplates/$CustomAppTemplateId/instantiate"
            Body        = @{ displayName = $ApplicationName }
            ErrorAction = 'Stop'

        }

        $NewApp = Invoke-MgGraphRequest @InstantiateRequest
        $AppCreated = $true

        # The beta endpoint returns objectId; v1.0 returns id
        $AppObjectId = If ($NewApp.application.objectId) { $NewApp.application.objectId } Else { $NewApp.application.id }
        $SpObjectId = If ($NewApp.servicePrincipal.objectId) { $NewApp.servicePrincipal.objectId } Else { $NewApp.servicePrincipal.id }

        If (-not $AppObjectId -or -not $SpObjectId) { Throw 'The application was created, but Graph did not return its object IDs. Find it in the Entra admin center and rerun with -UpdateExisting.' }

        Write-Verbose "Created application '$ApplicationName' ($AppObjectId), service principal $SpObjectId."

    }

    # Make it a Private Access (non-web) application
    If ($NeedsPublishing -and $PSCmdlet.ShouldProcess($ApplicationName, 'Enable as a Private Access application')) {

        $PublishingRequest = @{

            Method = 'PATCH'
            Uri    = "$GraphBeta/applications/$AppObjectId"
            Body   = @{

                onPremisesPublishing = @{

                    applicationType           = 'nonwebapp'
                    isAccessibleViaZTNAClient = $true

                }

            }

        }

        Invoke-GraphRequestWithRetry -Request $PublishingRequest | Out-Null
        Write-Verbose 'Enabled the application for Private Access.'

    }

    # Device Access lets Windows devices reach the domain controllers before a user signs in
    If ($EnableDeviceAccess -and -not $DeviceAccessEnabled) {

        If ($PSCmdlet.ShouldProcess($ApplicationName, 'Enable Device Access with Global Secure Access')) {

            # Send the Private Access settings with the change, so the update can't clear them
            $DeviceAccessRequest = @{

                Method = 'PATCH'
                Uri    = "$GraphBeta/applications/$AppObjectId"
                Body   = @{

                    onPremisesPublishing = @{

                        applicationType           = 'nonwebapp'
                        isAccessibleViaZTNAClient = $true
                        isDeviceAccessEnabled     = $true

                    }

                }

            }

            # Device Access is in preview. Record a failure and keep going, so the segments are still added
            Try {

                Invoke-GraphRequestWithRetry -Request $DeviceAccessRequest | Out-Null

                # Read the setting back to confirm the service applied it
                $VerifyRequest = @{

                    Method = 'GET'
                    Uri    = "$GraphBeta/applications/$($AppObjectId)?`$select=onPremisesPublishing"

                }

                $Verify = Invoke-GraphRequestWithRetry -Request $VerifyRequest

                If ($Verify.onPremisesPublishing.isDeviceAccessEnabled -eq $true) {

                    $DeviceAccessEnabled = $true
                    $DeviceAccessStatus = 'Enabled'
                    Write-Verbose 'Enabled Device Access with Global Secure Access.'

                }

                Else {

                    $DeviceAccessStatus = 'Not confirmed'
                    Write-Warning "Device Access was requested, but '$ApplicationName' does not report it as enabled. Check 'Enable Device Access with Global Secure Access' in the application's network access properties in the Entra admin center."

                }

            }

            Catch {

                $DeviceAccessStatus = 'Failed'
                Write-Warning "Unable to enable Device Access on '$ApplicationName'. $(Get-GraphErrorMessage -ErrorRecord $_) Device Access is in preview and may not be available in this tenant."

            }

        }

        Else {

            $DeviceAccessStatus = '(not enabled, -WhatIf)'

        }

    }

    # Bind the connector group (new applications, or existing ones with no group)
    If ($ConnectorGroup -and $PSCmdlet.ShouldProcess($ApplicationName, "Bind connector group '$($ConnectorGroup.name)'")) {

        $ConnectorGroupRequest = @{

            Method = 'PUT'
            Uri    = "$GraphBeta/applications/$AppObjectId/connectorGroup/`$ref"
            Body   = @{ '@odata.id' = "$GraphBeta/onPremisesPublishingProfiles/applicationproxy/connectorGroups/$($ConnectorGroup.id)" }

        }

        Invoke-GraphRequestWithRetry -Request $ConnectorGroupRequest | Out-Null
        $BoundGroupName = $ConnectorGroup.name
        $BoundGroupIsDefault = $ConnectorGroup.isDefault -eq $true
        $BoundActiveConnectors = $ConnectorGroup.activeConnectorCount
        Write-Verbose "Bound connector group '$($ConnectorGroup.name)'."

    }

    ElseIf ($ConnectorGroup) {

        $BoundGroupName = "$($ConnectorGroup.name) (not bound, -WhatIf)"
        $BoundGroupIsDefault = $ConnectorGroup.isDefault -eq $true
        $BoundActiveConnectors = $ConnectorGroup.activeConnectorCount

    }

    If ($BoundGroupIsDefault) {

        $DefaultGroupName = $ConnectorGroup.name

        If (-not $DefaultGroupName) { $DefaultGroupName = $BoundGroupName }

        # Mark a renamed default group. 'Default [default]' would be redundant
        If ($DefaultGroupName -ne 'Default') { $BoundGroupName += ' [default]' }

    }

    # Hide the application from users and require assignment. It is an infrastructure service
    # Existing applications keep an administrator's changes unless -ResetAppSettings is used
    $SpChanges = @{}

    If ($SpObjectId) {

        $SpRequest = @{

            Method = 'GET'
            Uri    = "$GraphBeta/servicePrincipals/$($SpObjectId)?`$select=tags,appRoleAssignmentRequired"

        }

        $Sp = Invoke-GraphRequestWithRetry -Request $SpRequest

        # Cast to [string[]] so the tags serialize as strings, not PSObject wrappers from the pipeline
        [string[]]$Tags = @($Sp.tags | Where-Object { $_ })

        # PATCH replaces the whole tags list, so keep the tags the template set
        If ($Tags -notcontains 'HideApp') { $SpChanges['tags'] = [string[]]($Tags + 'HideApp') }
        If (-not $Sp.appRoleAssignmentRequired) { $SpChanges['appRoleAssignmentRequired'] = $true }

        If ($SpChanges.Count -eq 0) { Write-Verbose 'The application is already hidden from users and requires assignment.' }

    }

    If (-not $IsNewApp -and $SpChanges.Count -gt 0 -and -not $ResetAppSettings) {

        If ($SpChanges.ContainsKey('tags')) { Write-Warning "'Visible to users' is Yes on '$ApplicationName'. It was not changed." }
        If ($SpChanges.ContainsKey('appRoleAssignmentRequired')) { Write-Warning "'Assignment required' is No on '$ApplicationName'. It was not changed." }

        Write-Warning 'Use -ResetAppSettings to hide the application from users and require assignment again.'

    }

    # A new application, or an existing one with -ResetAppSettings. With -WhatIf, a new application has no service principal yet
    ElseIf ($SpChanges.Count -gt 0 -or ($IsNewApp -and -not $SpObjectId)) {

        $HideAction = If ($IsNewApp) { 'Hide from users and require assignment' } Else { 'Restore hidden from users and assignment required settings' }

        If ($PSCmdlet.ShouldProcess($ApplicationName, $HideAction)) {

            $HideRequest = @{

                Method = 'PATCH'
                Uri    = "$GraphBeta/servicePrincipals/$SpObjectId"
                Body   = $SpChanges

            }

            Invoke-GraphRequestWithRetry -Request $HideRequest | Out-Null
            $AppSettingsApplied = $true
            Write-Verbose 'The application is hidden from users and requires assignment.'

        }

    }

    #EndRegion

    #Region Segments

    $SegmentsUri = "$GraphBeta/applications/$AppObjectId/onPremisesPublishing/segmentsConfiguration/microsoft.graph.ipSegmentConfiguration/applicationSegments"

    # Read the existing segments, keyed by host and type
    $ExistingSegments = @()

    If ($AppObjectId -and -not $AppCreated) {

        $ExistingSegments = @(Get-GraphCollection -Uri $SegmentsUri)

    }

    # Build the segments to publish: FQDN and IPv4 address, TCP and UDP
    $Segments = ForEach ($Dc in $DcList.Values) {

        # Graph documents 'ipAddress', but the service only accepts 'ip' (the same value the Entra Beta module sends)
        ForEach ($Target in @(@{ Host = $Dc.HostName; Type = 'fqdn' }, @{ Host = $Dc.IPv4Address; Type = 'ip' })) {

            ForEach ($Protocol in $PortMap.Keys) {

                [PSCustomObject]@{

                    DomainController = $Dc.HostName
                    DestinationHost  = $Target.Host.ToLower()
                    DestinationType  = $Target.Type
                    Protocol         = $Protocol
                    Ports            = $PortMap[$Protocol]
                    Status           = 'Pending'
                    Message          = $null

                }

            }

        }

    }

    $MatchedExisting = [System.Collections.Generic.HashSet[string]]::new()
    $Index = 0

    ForEach ($Segment in $Segments) {

        $Index++
        $ProgressParams = @{

            Activity        = "Publishing domain controllers to '$ApplicationName'"
            Status          = "$($Segment.DestinationHost) ($($Segment.Protocol.ToUpper())), $Index of $(@($Segments).Count)"
            PercentComplete = [int](($Index - 1) / @($Segments).Count * 100)

        }

        Write-Progress @ProgressParams

        # Compare with segments already on the application
        # Treat 'ip' and 'ipAddress' as the same type, since Graph may return either
        $SameHost = @($ExistingSegments | Where-Object { $_.destinationHost -eq $Segment.DestinationHost -and ("$($_.destinationType)" -replace '^ipAddress$', 'ip') -eq $Segment.DestinationType -and (("$($_.protocol)" -split ',') -contains $Segment.Protocol) })

        If ($SameHost.Count -gt 0) {

            ForEach ($Existing in $SameHost) { [void]$MatchedExisting.Add($Existing.id) }

            $Exact = $SameHost | Where-Object { $_.protocol -eq $Segment.Protocol -and (Get-PortKey -Port $_.ports) -eq (Get-PortKey -Port $Segment.Ports) }

            If ($Exact) {

                $Segment.Status = 'Exists'

            }

            Else {

                $Segment.Status = 'Differs'
                $Segment.Message = "An existing $($SameHost[0].protocol) segment for this host has ports $(Get-PortKey -Port $SameHost[0].ports). It was not changed."
                Write-Warning "$($Segment.DestinationHost) ($($Segment.Protocol.ToUpper())): $($Segment.Message)"

            }

            Continue

        }

        If (-not $PSCmdlet.ShouldProcess($ApplicationName, "Add $($Segment.Protocol.ToUpper()) segment $($Segment.DestinationHost) ($($Segment.DestinationType)), ports $($Segment.Ports -join ', ')")) {

            $Segment.Status = 'WhatIf'
            Continue

        }

        $SegmentRequest = @{

            Method = 'POST'
            Uri    = $SegmentsUri
            Body   = @{

                destinationHost = $Segment.DestinationHost
                destinationType = $Segment.DestinationType
                protocol        = $Segment.Protocol
                ports           = $Segment.Ports

            }

        }

        # Record failures and keep going, so one conflict doesn't stop the run
        Try {

            Invoke-GraphRequestWithRetry -Request $SegmentRequest | Out-Null
            $Segment.Status = 'Created'

        }

        Catch {

            $Segment.Status = 'Failed'
            $Segment.Message = Get-GraphErrorMessage -ErrorRecord $_
            Write-Warning "Failed to add $($Segment.Protocol.ToUpper()) segment $($Segment.DestinationHost): $($Segment.Message)"

        }

    }

    Write-Progress -Activity "Publishing domain controllers to '$ApplicationName'" -Completed

    # Report segments on the application that this run did not cover. Nothing is deleted
    $OtherSegments = @($ExistingSegments | Where-Object { -not $MatchedExisting.Contains($_.id) })

    If ($OtherSegments.Count -gt 0) {

        $OtherList = ($OtherSegments | ForEach-Object { "$($_.destinationHost) ($($_.protocol))" } | Sort-Object -Unique) -join ', '
        Write-Information "The application has $($OtherSegments.Count) segment(s) not part of this run. They were not changed: $OtherList" -InformationAction Continue

    }

    #EndRegion

    #Region Summary

    $FailedCount = @($Segments | Where-Object { $_.Status -eq 'Failed' }).Count

    Write-Information '' -InformationAction Continue
    Write-Information "Application: $ApplicationName" -InformationAction Continue
    Write-Information "Application ID: $(If ($AppObjectId) { $AppObjectId } Else { '(not created, -WhatIf)' })" -InformationAction Continue
    Write-Information "Service principal: $(If ($SpObjectId) { $SpObjectId } Else { '(not created, -WhatIf)' })" -InformationAction Continue
    Write-Information "Connector group: $BoundGroupName" -InformationAction Continue
    Write-Information "Device access: $DeviceAccessStatus" -InformationAction Continue
    Write-Information '' -InformationAction Continue
    # A dry run has no next steps beyond running it for real
    If ($WhatIfPreference) {

        $WhatIfAction = If ($IsNewApp) { 'create the application' } Else { 'apply these changes' }
        Write-Information "Run without -WhatIf to $WhatIfAction." -InformationAction Continue

    }

    Else {

        Write-Information 'Next steps:' -InformationAction Continue
        Write-Information ' - The application is NOT assigned to anyone. Review it in the Entra admin center (Global Secure Access > Applications > Enterprise applications), then assign synchronized users or groups if approved.' -InformationAction Continue
        Write-Information ' - Confirm Private DNS is enabled in Quick Access with the forest''s DNS suffixes.' -InformationAction Continue

        If ($DeviceAccessEnabled) {

            Write-Information ' - Add the application to a Device Access profile and assign the profile to Microsoft Entra joined or hybrid joined Windows devices. If Private DNS is configured in Quick Access, also enable Device Access on Quick Access and include it in the profile.' -InformationAction Continue

        }

        # The default group should be a staging group. Active connectors there mean it is carrying traffic
        If ($BoundGroupIsDefault -and $BoundActiveConnectors -gt 0) {

            Write-Information " - The application is assigned to the default connector group '$DefaultGroupName', which has $BoundActiveConnectors active connector(s). Best practice is to use the default group only for staging. Consider moving these connectors to a connector group for their AD site, then reassigning the application to that group." -InformationAction Continue

        }

    }

    If ($BoundGroupIsDefault -and $BoundActiveConnectors -eq 0) {

        $AssignedText = If ($ConnectorGroup -and $WhatIfPreference) { 'would be assigned' } Else { 'is assigned' }
        Write-Warning "The application $AssignedText to the default connector group '$DefaultGroupName', which has no active connectors. Clients can't reach the domain controllers until the application is reassigned to the connector group for the domain controllers' AD site. Reassign it in the Entra admin center when that group is ready."

    }

    If ($AllDomainControllers) {

        Write-Warning 'This application includes every domain controller in the forest. Before assigning the application, delete the segments for domain controllers outside the AD site where the Private Access connectors are installed. The Site column below identifies each domain controller''s site.'

    }

    If ($FailedCount -gt 0) {

        Write-Warning "$FailedCount segment(s) failed. Fix the cause shown above, then rerun the script with -UpdateExisting to add the missing segments."
        $ExitCode = 1

    }

    If ($DeviceAccessStatus -in 'Failed', 'Not confirmed') {

        Write-Warning 'Device Access is not enabled. Fix the cause shown above, then rerun the script with -UpdateExisting -EnableDeviceAccess, or enable it in the Entra admin center.'
        $ExitCode = 1

    }

    # One summary row per domain controller
    ForEach ($Dc in $DcList.Values) {

        $DcSegments = @($Segments | Where-Object { $_.DomainController -eq $Dc.HostName })

        [PSCustomObject]@{

            DomainController = $Dc.HostName
            Domain           = $Dc.Domain
            Site             = $Dc.Site
            IPv4Address      = $Dc.IPv4Address
            Created          = @($DcSegments | Where-Object { $_.Status -eq 'Created' }).Count
            Existing         = @($DcSegments | Where-Object { $_.Status -eq 'Exists' }).Count
            Differs          = @($DcSegments | Where-Object { $_.Status -eq 'Differs' }).Count
            Failed           = @($DcSegments | Where-Object { $_.Status -eq 'Failed' }).Count
            WhatIf           = @($DcSegments | Where-Object { $_.Status -eq 'WhatIf' }).Count

        }

    }

    #EndRegion

}

Catch {

    # Point to the recovery path when the application was created but setup did not finish
    If ($AppCreated) {

        # Without -ResetAppSettings, a rerun keeps the template's visible, no-assignment settings
        $RecoverySwitches = If ($AppSettingsApplied) { '-UpdateExisting' } Else { '-UpdateExisting -ResetAppSettings' }
        Write-Warning "The application '$ApplicationName' was created but setup did not finish. Fix the cause, then rerun the script with $RecoverySwitches."

    }

    # Record the error in the transcript before logging stops
    $ErrorActionPreference = 'Continue'
    Write-Error -ErrorRecord $_
    $ExitCode = 1

}

Finally {

    # Stop-Transcript supports -WhatIf in PowerShell 7 but not in Windows PowerShell 5.1
    $StopTranscriptParams = @{}

    If ((Get-Command -Name Stop-Transcript).Parameters.ContainsKey('WhatIf')) {

        $StopTranscriptParams = @{ WhatIf = $false; Confirm = $false }

    }

    Stop-Transcript @StopTranscriptParams | Out-Null

}

If ($ExitCode -ne 0) {

    Exit $ExitCode

}