Public/Invoke-IntuneBackupDeviceCompliancePolicySP.ps1

function Invoke-IntuneBackupDeviceCompliancePolicySP {
    <#
    .SYNOPSIS
    Backup Intune Device Compliance Policies
     
    .DESCRIPTION
    Backup Intune Device Compliance Policies as JSON files per Device Compliance Policy to the specified Path.
     
    .PARAMETER Path
    Path to store backup files
     
    .EXAMPLE
    Invoke-IntuneBackupDeviceCompliancePolicy -Path "C:\temp"
    #>

    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Path,

        [Parameter(Mandatory = $false)]
        [ValidateSet("v1.0", "Beta")]
        [string]$ApiVersion = "Beta"
    )

    # Ensure the Microsoft Graph module is installed and imported
    if (-not (Get-Module -Name Microsoft.Graph -ListAvailable)) {
        Install-Module -Name Microsoft.Graph -Scope CurrentUser -Force
    }
    Import-Module Microsoft.Graph.DeviceManagement

    # Connect to Microsoft Graph if not already connected
    if (-not (Get-MgUser -UserId me -ErrorAction SilentlyContinue)) {
        Connect-MgGraph -Scopes "DeviceManagementApps.Read.All","DeviceManagementApps.ReadWrite.All","DeviceManagementConfiguration.Read.All","DeviceManagementConfiguration.ReadWrite.All","DeviceManagementServiceConfig.Read.All","DeviceManagementServiceConfig.ReadWrite.All"
        
    }

    
    # Function to get all pages of results
    function Get-AllPages {
        param (
            [Parameter(Mandatory = $true)]
            [string]$Uri
        )

        $results = @()
        $response = Invoke-MgGraphRequest -Method GET -Uri $Uri
        $results += $response.value

        while ($null -ne $response.'@odata.nextLink') {
            $response = Invoke-MgGraphRequest -Method GET -Uri $response.'@odata.nextLink'
            $results += $response.value
        }

        return $results
    }

    # Create folder if not exists
    if (-not (Test-Path "$Path\Device Compliance Policies")) {
        $null = New-Item -Path "$Path\Device Compliance Policies" -ItemType Directory
    }

    # Get all Device Compliance Policies
    $deviceCompliancePolicies =@()
    $deviceCompliancePolicies= Get-allpages -Uri "https://graph.microsoft.com/$ApiVersion/deviceManagement/deviceCompliancePolicies"
    
    foreach ($deviceCompliancePolicy in $deviceCompliancePolicies) {
        $fileName = ($deviceCompliancePolicy.displayName).Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
        $deviceCompliancePolicy | ConvertTo-Json -Depth 100 | Out-File -LiteralPath "$path\Device Compliance Policies\$fileName.json"

        [PSCustomObject]@{
            "Action" = "Backup"
            "Type"   = "Device Compliance Policy"
            "Name"   = $deviceCompliancePolicy.displayName
            "Path"   = "Device Compliance Policies\$fileName.json"
        }
    }
}