Last active
February 5, 2024 11:01
-
-
Save JayVDZ/b885118562b3be6b7512f922120853d6 to your computer and use it in GitHub Desktop.
Export-CAPolicies.ps1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
Export-CAPolicies.ps1 | |
.DESCRIPTION | |
Export Conditional Access policies to JSON files for backup purposes. | |
.LINK | |
www.alitajran.com/export-conditional-access-policies/ | |
.NOTES | |
Written by: ALI TAJRAN | |
Website: www.alitajran.com | |
LinkedIn: linkedin.com/in/alitajran | |
.CHANGELOG | |
V1.00, 11/16/2023 - Initial version | |
V1.10, 05/02/2024 - @JayVDZ: Fix: policies with file-system invalid characters cause export failures using code from Alexander. | |
V1.20, 05/02/2024 - @JayVDZ: Fix: folder not existing causes script failure. | |
#> | |
# Connect to Microsoft Graph API | |
Connect-MgGraph -Scopes 'Policy.Read.All' | |
# Export path for CA policies | |
$ExportPath = "C:\temp\conditional-access-policies" | |
# Make sure the export path exists | |
if (!(Test-Path $ExportPath)) { | |
New-Item -ItemType Directory -Force -Path $ExportPath | Out-Null | |
} | |
try | |
{ | |
# Retrieve all conditional access policies from Microsoft Graph API | |
$AllPolicies = Get-MgIdentityConditionalAccessPolicy -All | |
if ($AllPolicies.Count -eq 0) | |
{ | |
Write-Host "There are no CA policies found to export." -ForegroundColor Yellow | |
} | |
else | |
{ | |
# Characters that will cause file operation issues | |
$SpecialChars = @('#','$','%','^','&','*','@','!',':','[',']', '\', '/') | |
# Iterate through each policy | |
foreach ($Policy in $AllPolicies) | |
{ | |
try | |
{ | |
# Get the display name of the policy | |
$PolicyName = $Policy.DisplayName | |
# Convert the policy object to JSON with a depth of 6 | |
$PolicyJSON = $Policy | ConvertTo-Json -Depth 6 | |
# Write the JSON to a file in the export path | |
$PolicyFileName = $PolicyName | |
ForEach ($Character in $SpecialChars) { | |
$PolicyFileName = $PolicyFileName.Replace($Character, '') | |
} | |
$PolicyJSON | Out-File "$ExportPath\$PolicyFileName.json" -Force | |
# Print a success message for the policy backup | |
Write-Host "Successfully backed up CA policy: $($PolicyFileName)" -ForegroundColor Green | |
} | |
catch | |
{ | |
# Print an error message for the policy backup | |
Write-Host "Error occurred while backing up CA policy: $($Policy.DisplayName). $($_.Exception.Message)" -ForegroundColor Red | |
} | |
} | |
} | |
} | |
catch | |
{ | |
# Print a generic error message | |
Write-Host "Error occurred: $($_.Exception.Message)" -ForegroundColor Red | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment