Public/Invoke-IntuneRestoreDeviceManagementIntent.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function Invoke-IntuneRestoreDeviceManagementIntent {
    <#
    .SYNOPSIS
    Restore Intune Device Management Intents
     
    .DESCRIPTION
    Restore Intune Device Management Intents from JSON files per Device Management Intent from the specified Path.
     
    .PARAMETER Path
    Root path where backup files are located, created with the Invoke-IntuneBackupDeviceManagementIntent function
     
    .EXAMPLE
    Invoke-IntuneRestoreDeviceManagementIntent -Path "C:\temp" -RestoreById $true
    #>

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

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

    # Set the Microsoft Graph API endpoint
    if (-not ((Get-MSGraphEnvironment).SchemaVersion -eq $apiVersion)) {
        Update-MSGraphEnvironment -SchemaVersion $apiVersion -Quiet
        Connect-MSGraph -ForceNonInteractive -Quiet
    }

    # Get all device management intents
    $deviceManagementIntents = Get-ChildItem -Path "$Path\Device Management Intents" -Recurse -File
    foreach ($deviceManagementIntent in $deviceManagementIntents) {
        $deviceManagementIntentContent = Get-Content -LiteralPath $deviceManagementIntent.FullName -Raw
        $deviceManagementIntentDisplayName = ($deviceManagementIntentContent | ConvertFrom-Json).displayName
        $templateId = $deviceManagementIntent.Name.Split("_")[0]
        $templateDisplayName = $deviceManagementIntent.Name.Split("_")[1]

        # Restore the device management intent
        try {
            $null = Invoke-MSGraphRequest -HttpMethod POST -Url "deviceManagement/templates/$($templateId)/createInstance" -Content $deviceManagementIntentContent.toString() -ErrorAction Stop
            Write-Output "$deviceManagementIntentDisplayName - Successfully restored Device Management Intent ($templateDisplayName)"
        }
        catch {
            Write-Output "$deviceManagementIntentDisplayName - Failed to restore Device Management Intent ($templateDisplayName)"
            Write-Error $_ -ErrorAction Continue
        }
    }
}