Skip to content

How to import Conditional Access policies

We want to import Conditional Access policies into the Microsoft Entra tenant. Now, we can restore Conditional Access policies using the Microsoft Entra admin center. But that’s a single Conditional Access policy upload. What if you have multiple Conditional Access policies that you want to import? PowerShell is the easiest and fastest way. In this article, you will learn how to import Conditional Access policies from a JSON file into Microsoft Entra with Microsoft Graph PowerShell.

Before you start

You need to have the Conditional Access policies in JSON files because the script will go through the JSON files and import them into the Microsoft Entra tenant.

If you already have the JSON files, you are good to go. If not, read more about How to export Conditional Access policies.

Install Microsoft Graph PowerShell

Before we can proceed further and restore all the Conditional Access policies into the Microsoft Entra tenant, we need to Install Microsoft Graph PowerShell.

Start Windows PowerShell as administrator and run the below commands.

Install-Module Microsoft.Graph -Force
Install-Module Microsoft.Graph.Beta -AllowClobber -Force

Important: Always install the Microsoft Graph PowerShell and Microsoft Graph Beta PowerShell modules. That’s because some cmdlets are not yet available in the final version, and they will not work. Update both modules to the latest version before you run a cmdlet or script to prevent errors and incorrect results.

Now that we have the Microsoft Graph PowerShell SDK module installed, we can go to the next step.

Prepare Import-CAPolicies PowerShell script

Create two folders on the (C:) drive:

  • Temp
  • Scripts

Download and place Import-CAPolicies.ps1 PowerShell script in the C:\scripts folder. The script will import the JSON files that are present in C:\temp folder into the Microsoft Entra tenant.

Ensure the file is unblocked to prevent errors when running the script. Read more in the article Not digitally signed error when running PowerShell script.

Another option is to copy and paste the below code into Notepad. Give it the name Import-CAPolicies.ps1 and place it in the C:\scripts folder.

<#
    .SYNOPSIS
    Import-CAPolicies.ps1

    .DESCRIPTION
    Import Conditional Access policies from JSON files for restore purposes.

    .LINK
    www.alitajran.com/import-conditional-access-policies/

    .NOTES
    Written by: ALI TAJRAN
    Website:    www.alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .CHANGELOG
    V1.00, 11/19/2023 - Initial version
#>

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Policy.Read.All", "Policy.ReadWrite.ConditionalAccess", "Application.Read.All"

# Define the path to the directory containing your JSON files
$jsonFilesDirectory = "C:\temp\"

# Get all JSON files in the directory
$jsonFiles = Get-ChildItem -Path $jsonFilesDirectory -Filter *.json

# Check if there are no JSON files
if ($jsonFiles.Count -eq 0) {
    Write-Host "No JSON files found in the directory to import." -ForegroundColor Yellow
}
else {
    # Loop through each JSON file
    foreach ($jsonFile in $jsonFiles) {
        try {
            # Read the content of the JSON file and convert it to a PowerShell object
            $policyJson = Get-Content -Path $jsonFile.FullName | ConvertFrom-Json

            # Create a custom object
            $policyObject = [PSCustomObject]@{
                displayName     = $policyJson.displayName
                conditions      = $policyJson.conditions
                grantControls   = $policyJson.grantControls
                sessionControls = $policyJson.sessionControls
                state           = $policyJson.state
            }

            # Convert the custom object to JSON with a depth of 10
            $policyJsonString = $policyObject | ConvertTo-Json -Depth 10

            # Create the Conditional Access policy using the Microsoft Graph API
            $null = New-MgIdentityConditionalAccessPolicy -Body $policyJsonString
        
            # Print a success message
            Write-Host "Policy created successfully: $($policyJson.displayName) " -ForegroundColor Green
        }
        catch {
            # Print an error message if an exception occurs
            Write-Host "An error occurred while creating the policy: $_" -ForegroundColor Red
        }
    }
}

This is how it looks.

Import Conditional Access policies scripts folder

Prepare Conditional Access JSON files

Ensure that all the CA policies JSON files are present in C:\temp.

Import Conditional Access policies JSON files

Remove all Conditional Access policies with PowerShell

We have many CA policies available in our Microsoft Entra tenant, and we want to remove them. Suppose you want to keep the policies that are already present, or it’s already empty, you can skip this step.

Let’s remove all the CA policies with the Remove-CAPolicies.ps1 PowerShell script.

<#
    .SYNOPSIS
    Remove-CAPolicies.ps1

    .DESCRIPTION
    Remove all Conditional Access policies from Microsoft Entra.

    .LINK
    www.alitajran.com/import-conditional-access-policies/

    .NOTES
    Written by: ALI TAJRAN
    Website:    www.alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .CHANGELOG
    V1.00, 11/19/2023 - Initial version
#>

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Policy.Read.All", "Policy.ReadWrite.ConditionalAccess", "Application.Read.All"

# Get all policies
$policies = Get-MgIdentityConditionalAccessPolicy -All

# Check if there are any policiesX
if ($policies.Count -eq 0) {
    Write-Host "There are no Conditional Access policies to delete." -ForegroundColor Yellow
}
else {
    # Loop through each policy and delete it
    foreach ($policy in $policies) {
        Remove-MgIdentityConditionalAccessPolicy -ConditionalAccessPolicyId $policy.Id
        Write-Host "Policy deleted successfully: $($policy.DisplayName)" -ForegroundColor Green
    }
}

Now that there are no more Conditional Access policies in the Microsoft Entra tenant, let’s add the CA policies by importing the JSON files.

Run Import Conditional Access policies PowerShell script

Run the Import-CAPolicies.ps1 PowerShell script to get all the Conditional Access JSON policies in C:\temp folder and import them to the Microsoft Entra tenant.

C:\scripts\Import-CAPolicies.ps1

Note: If you already have the CA policies in Microsoft Entra, it will not overwrite them or check if the policy is present. It will add the policy with the same name, and you can recognize them when you look at the Creation Date. You can remove the policies that are already present or disable them.

The output shows:

Policy created successfully: Block legacy authentication
Policy created successfully: Require multifactor authentication for all users

Verify Conditional Access policies

Check that the Conditional Access policies are successfully imported with PowerShell. Run the Get-MgIdentityConditionalAccessPolicy cmdlet.

Get-MgIdentityConditionalAccessPolicy -All

This is how it looks in our example.

Id                                   CreatedDateTime       Description DisplayName                                      ModifiedDateTime State
--                                   ---------------       ----------- -----------                                      ---------------- -----
a800fccb-1912-45b6-ad7b-634e60a33c6c 11/19/2023 5:14:01 PM             Block legacy authentication                                       disabled
6bfb32e1-92cf-40fb-8fce-0143bcb39584 11/19/2023 5:14:02 PM             Require multifactor authentication for all users                  enabled

Another way to verify that the Conditional Access policies are imported successfully is with Microsoft Entra admin center:

  1. Sign in to Microsoft Entra admin center
  2. Expand Identity > Protection
  3. Click on Conditional Access
  4. Select View all policies

In our example, there are two CA policies. One of the policies is enabled, and the other one is disabled.

Import Conditional Access policies Entra admin center

Everything looks great!

Did this help you to restore Conditional Access policies from JSON files to Microsoft Entra tenant?

Read more: Get MFA status in Microsoft Entra and PowerShell »

Conclusion

You learned how to import Conditional Access policies with PowerShell. It’s faster to import the CA policies with PowerShell if you have more than one CA policy. First, connect to Microsoft Graph PowerShell and run the Import-CAPolicies PowerShell script. After that, all the Conditional Access policies and their configurations are available in Microsoft Entra.

Did you enjoy this article? You may also like Export Azure AD users to CSV with PowerShell. Don’t forget to follow us and share this article.

ALI TAJRAN

ALI TAJRAN

ALI TAJRAN is a passionate IT Architect, IT Consultant, and Microsoft Certified Trainer. He started Information Technology at a very young age, and his goal is to teach and inspire others. Read more »

This Post Has 2 Comments

  1. Hi Ali

    I just tried to import the policies, on the line with
    $null = New-MgIdentityConditionalAccessPolicy …. I got the error “You cannot perform the requested operation, required scopes are missing in the token.”

    I have not yet figured out why I get this error/what it means. Do you have any idea?

Leave a Reply

Your email address will not be published. Required fields are marked *