$backupDir = "C:\AAD_CA" if (!(Test-Path $backupDir)){mkdir $backupDir} Connect-AzureAD function Import-AADCABackups { gci -File -Recurse $backupDir -Include *.json | % { [pscustomobject]@{ ID = ($_.Name.Split("_"))[0] Version =[datetime]::ParseExact( ($_.BaseName.Split("_"))[1], 'yyyyMMddHHmm', $null) JSON = Get-Content $_.FullName Name = (Get-item $_.Directory).Name } } } function Backup-AADCAs { Param( [Parameter(Mandatory=$false)] [switch]$ChangedOnly ) $import_CABackups = Import-AADCABackups $AAD_CAs = Get-AzureADMSConditionalAccessPolicy $strDate = Get-date -Format yyyyMMddHHmm foreach ($CA in $AAD_CAs){ #create backup directory if it does not exist if (!(Test-Path "$backupDir\$($CA.displayname)")){New-item -ItemType Directory -Path "$backupDir\$($CA.displayname)" >> $null } #load JSON $CA_JSON = $CA | ConvertTo-Json -Depth 6 -Compress #Export changes only if ($ChangedOnly){ $import_CABackup_latest_JSON = ($import_CABackups.where({$_.ID -eq $CA.id}) | sort version | select -Last 1).JSON #New CA if ($import_CABackup_latest_JSON -eq $null){ Write-Host "New policy found: $($CA.DisplayName)" -ForegroundColor Green Out-File -InputObject $CA_JSON -Encoding utf8 -FilePath "$backupDir\$($CA.displayname)\$($ca.id)_$strdate.json" } #Difference found if (([bool]$import_CABackup_latest_JSON) -and ($import_CABackup_latest_JSON -ne $CA_JSON)){ Write-Host "Found difference for $($CA.DisplayName)" -ForegroundColor Yellow Out-File -InputObject $CA_JSON -Encoding utf8 -FilePath "$backupDir\$($CA.displayname)\$($ca.id)_$strdate.json" } #No difference found if (([bool]$import_CABackup_latest_JSON) -and ($import_CABackup_latest_JSON -eq $CA_JSON)){ Write-Host "No difference found for $($CA.DisplayName)" -ForegroundColor Cyan } #Export all }else{ Out-File -InputObject $CA_JSON -Encoding utf8 -FilePath "$backupDir\$($CA.displayname)\$($ca.id)_$strdate.json" } } #Deleted CA $import_CABackups | ? {$_.id -notin $AAD_CAs.id} | % { Write-Host "Policy deleted in AzureAD: $($_.Name)" -ForegroundColor Red } } Backup-AADCAs -ChangedOnly #Export changed Conditional Access policies only #Backup-AADCAs - to export all CAs whether they are changed or not