backup/Backup-CustomAttributes.ps1
|
#Requires -Version 7.0 function Backup-CustomAttributes { [CmdletBinding()] param( [Parameter(Mandatory)] [string]$BackupPath, [Parameter(Mandatory)] [SecureString]$Token, [hashtable]$ScopeTagMap = @{} ) try { $folder = Join-Path $BackupPath 'Custom Attributes' $scriptFolder = Join-Path $folder 'Script Data' $uri = '/beta/deviceManagement/deviceCustomAttributeShellScripts/' $items = Invoke-GraphRequest2 -Uri $uri -Token $Token foreach ($item in $items) { # fetch full details $fullUri = "/beta/deviceManagement/deviceCustomAttributeShellScripts/$($item.id)" $fullItem = Invoke-GraphRequest2 -Uri $fullUri -Token $Token # decode and save script content if ($fullItem.scriptContent) { $scriptBytes = [System.Convert]::FromBase64String($fullItem.scriptContent) $scriptContent = [System.Text.Encoding]::UTF8.GetString($scriptBytes) $scriptFileName = ConvertTo-SanitizatedFileName -fileName$fullItem.fileName $noExtension = [System.IO.Path]::GetFileNameWithoutExtension($scriptFileName) $scriptPath = Join-Path $scriptFolder "$noExtension.sh" New-Item -ItemType Directory -Path $scriptFolder -Force | Out-Null Set-Content -Path $scriptPath -Value $scriptContent -Encoding UTF8 } # fetch and attach assignments $assignments = Resolve-Assignments -AssignmentsUri "/beta/deviceManagement/deviceCustomAttributeShellScripts/$($item.id)/assignments" -Token $Token if ($assignments) { $fullItem | Add-Member -MemberType NoteProperty -Name 'assignments' -Value $assignments -Force } # save metadata JSON without the script content $clean = Remove-VolatileKeys -InputObject $fullItem $clean | Add-Member -MemberType NoteProperty -Name 'scriptContent' -Value $null -Force Save-BackupItem -Item $clean -Folder $folder -ScopeTagMap $ScopeTagMap } Write-Verbose "backed up $($items.Count) custom attributes to $folder" } catch { Write-Error "failed to backup custom attributes: $_" return } } Export-ModuleMember -Function Backup-CustomAttributes |