Private/Remove-IntunePolicyByDisplayName.ps1

<#
.SYNOPSIS
    Removes an Intune policy by displayName if it exists.
.DESCRIPTION
    Searches for and deletes a policy with the specified displayName from Intune.
    Supports both device configuration policies and compliance policies.
.PARAMETER DisplayName
    The displayName of the policy to remove.
.PARAMETER PolicyType
    Type of policy: "Configuration" (default), "Compliance", or "AppProtection"
.OUTPUTS
    Boolean indicating if a policy was found and deleted
#>

function Remove-IntunePolicyByDisplayName {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$DisplayName,
        
        [Parameter(Mandatory=$false)]
        [ValidateSet("Configuration", "Compliance", "AppProtection")]
        [string]$PolicyType = "Configuration"
    )

    try {
        if ($PolicyType -eq "Compliance") {
            $uri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies"
        }
        elseif ($PolicyType -eq "AppProtection") {
            $uri = "https://graph.microsoft.com/v1.0/deviceAppManagement/managedAppPolicies"
        }
        else {
            $uri = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations"
        }

        # Get all policies with pagination
        $allPolicies = @()
        $nextLink = $uri

        do {
            $response = Invoke-IntuneGraphRequest -Method GET -Uri $nextLink -ErrorAction Stop
            if ($response.value) {
                $allPolicies += $response.value
            }
            $nextLink = $response.'@odata.nextLink'
        } while ($nextLink)

        # Find exact match by displayName
        $existingPolicy = $allPolicies | Where-Object { $_.displayName -eq $DisplayName } | Select-Object -First 1

        if ($existingPolicy) {
            Write-Verbose "Found existing policy: $DisplayName (ID: $($existingPolicy.id))"
            try {
                $deleteUri = "$uri/$($existingPolicy.id)"
                Invoke-IntuneGraphRequest -Method DELETE -Uri $deleteUri -ErrorAction Stop
                Write-Verbose "Deleted existing policy: $DisplayName"
                return $true
            }
            catch {
                Write-Warning "Failed to delete existing policy '$DisplayName': $_"
                return $false
            }
        }
        else {
            Write-Verbose "No existing policy found with displayName: $DisplayName"
            return $false
        }
    }
    catch {
        Write-Verbose "Error checking for existing policy '$DisplayName': $_"
        return $false
    }
}