Public/Invoke-IntuneRestoreDeviceShellScriptSP.ps1
function Invoke-IntuneRestoreDeviceShellScriptSP { <# .SYNOPSIS Restore Intune Device Shell Scripts (Used by macOS) .DESCRIPTION Restore Intune Device Shell Scripts (Used by macOS) from JSON files per Device Management Script from the specified Path. .PARAMETER Path Root path where backup files are located, created with the Invoke-IntuneBackupDeviceManagementScript function .EXAMPLE Invoke-IntuneRestoreDeviceManagementScript -Path "C:\temp" -RestoreById $true #> [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 } # Get all device management scripts $deviceShellScripts = Get-ChildItem -Path "$Path\Device Shell Scripts" -File foreach ($deviceShellScript in $deviceShellScripts) { $deviceShellScriptContent = Get-Content -LiteralPath $deviceShellScript.FullName -Raw $deviceShellScriptDisplayName = ($deviceShellScriptContent | ConvertFrom-Json).displayName # Remove properties that are not available for creating a new configuration $requestBodyObject = $deviceShellScriptContent | ConvertFrom-Json $requestBody = $requestBodyObject | Select-Object -Property * -ExcludeProperty id, createdDateTime, lastModifiedDateTime | ConvertTo-Json # Restore the device management script try { $null = Invoke-MGGraphRequest -Method POST -Body $requestBody -Uri "$apiVersion/deviceManagement/deviceShellScripts" -ContentType 'application/json' -ErrorAction Stop [PSCustomObject]@{ "Action" = "Restore" "Type" = "Device Shell Script" "Name" = $deviceShellScriptDisplayName "Path" = "Device Shell Scripts\$($deviceShellScript.Name)" } } catch { Write-Verbose "$deviceShellScriptDisplayName - Failed to restore Device Shell Script" -Verbose Write-Error $_ -ErrorAction Continue } } } |