Public/Invoke-IntuneRestoreClientAppAssignment.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
function Invoke-IntuneRestoreClientAppAssignment {
    <#
    .SYNOPSIS
    Restore Intune Client App Assignments (excluding managedAndroidStoreApp and managedIOSStoreApp)
     
    .DESCRIPTION
    Restore Intune Client App Assignments from JSON files per Client App from the specified Path.
     
    .PARAMETER Path
    Root path where backup files are located, created with the Invoke-IntuneBackupClientAppAssignment function
 
    .PARAMETER RestoreById
    If RestoreById is set to false, assignments will be restored to Intune Client Apps that match the file name.
    This is necessary if the Client App was restored from backup, because then a new Client App is created with a new unique ID.
     
    .EXAMPLE
    Invoke-IntuneRestoreClientAppAssignment -Path "C:\temp" -RestoreById $true
    #>

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

        [Parameter(Mandatory = $false)]
        [bool]$RestoreById = $true,

        [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 policies with assignments
    $clientApps = Get-ChildItem -Path "$Path\Client Apps\Assignments"
    foreach ($clientApp in $clientApps) {
        $clientAppAssignments = Get-Content -LiteralPath $clientApp.FullName | ConvertFrom-Json
        $clientAppId = ($clientApp.BaseName -split " - ")[0]
        $clientAppName = ($clientApp.BaseName -split " - ")[1]

        # Create the base requestBody
        $requestBody = @{
            mobileAppAssignments = @()
        }
        
        # Add assignments to restore to the request body
        foreach ($clientAppAssignment in $clientAppAssignments) {

            $clientAppAssignment.settings.installTimeSettings.PSObject.Properties | Foreach-Object {
                if ($null -ne $_.Value) {
                    if ($_.Value.GetType().Name -eq "DateTime") {
                        $_.Value = (Get-Date -Date $_.Value -Format s) + "Z"
                    }
                }
            }

            $requestBody.mobileAppAssignments += @{
                "target"   = $clientAppAssignment.target
                "intent"   = $clientAppAssignment.intent
                "settings" = $clientAppAssignment.settings
            }
        }

        # Convert the PowerShell object to JSON
        $requestBody = $requestBody | ConvertTo-Json -Depth 5

        # Get the Client App we are restoring the assignments for
        try {
            if ($restoreById) {
                $clientAppObject = Get-DeviceAppManagement_MobileApps -mobileAppId $clientAppId
            }
            else {
                $clientAppObject = Get-DeviceAppManagement_MobileApps | Get-MSGraphAllPages | Where-Object { $_.displayName -eq "$($clientAppName)" -and $_.'@odata.type' -ne "#microsoft.graph.managedAndroidStoreApp" -and $_.'@odata.type' -ne "#microsoft.graph.managedIOSStoreApp" }
                if (-not ($clientAppObject)) {
                    Write-Warning "Error retrieving Intune Client App for $($clientApp.FullName). Skipping assignment restore"
                    continue
                }
            }
        }
        catch {
            Write-Output "Error retrieving Intune Client App for $($clientApp.FullName), does it exist in the Intune tenant? Skipping assignment restore ..."
            Write-Error $_ -ErrorAction Continue
            continue
        }

        # Restore the assignments
        try {
            $null = Invoke-MSGraphRequest -HttpMethod POST -Content $requestBody.toString() -Url "deviceAppManagement/mobileApps/$($clientAppObject.id)/assign" -ErrorAction Stop
            Write-Output "$($clientAppObject.displayName) - Successfully restored Client App Assignment(s)"
        }
        catch {
            if ($_.Exception.Message -match "The MobileApp Assignment already exist") {
                Write-Output "$($clientAppObject.displayName) - The Client App Assignment already exists"
            }
            else {
                Write-Output "$($clientAppObject.displayName) - Failed to restore Client App Assignment(s)"
                Write-Error $_ -ErrorAction Continue
            }
        }
    }
}