Automate Intune Device Group Creation Based on Your OU Structure

Say goodbye to manually creating Dynamic Device Groups and Group Tags


As IT administrators shift from traditional Active Directory environments to cloud-native Intune management, one common frustration emerges:

πŸ›‘ β€œI have dozens of OUs… and I need matching Dynamic Device Groups in Intune for policies, apps, and compliance rules. This is going to take forever.”

That’s where this script comes in.


πŸ’‘ Purpose of the Script

Instead of manually setting up Dynamic Device Groups (DDGs) and Group Tags one by one, the Intune-DDG-AutoCreator.ps1 script automates the entire process.

With a single command and a .txt file of your OU names, the script will:

  • βœ… Read your OU names
  • βœ… Automatically generate DDGs in Microsoft Entra (Azure AD)
  • βœ… Apply Autopilot Group Tags as part of the group logic
  • βœ… Save hours of repetitive work

πŸ› οΈ How It Works

  1. You provide a .txt file containing your OU names
    (e.g., School-Site01, Finance, HR, etc.)
  2. The script:
  • Prompts you for a group name prefix
  • Builds Dynamic Device Groups
  • Applies a dynamic filter using devicePhysicalIds or GroupTag
  1. Result: Cloud-native groups you can use for:
  • App assignments
  • Policy deployments
  • Compliance targeting
  • Autopilot profile filtering

πŸ“ Example Input File: ou.txt

As an Example elts say we have this:

Domain.local
└── OFFICE-Site-01
    └── S01 (SITECODE#)
        └── S01-RM01 (Site+Room#)
            └── S01-RM01-CRT01 (Site+Room#+CART#)

CYBERSYSTEM

School-Site-01

S01

S01-RM01

S01-RM01-CRT01


πŸ’» How to Use the Script

.\Intune-DDG-Autocreator.ps1

πŸ“Œ Example Group Filter Created

(device.devicePhysicalIds -any _ -eq "[OrderId]:CYBERSYSTEM")

(device.devicePhysicalIds -any _ -eq "[OrderId]:Office-Site01")

(device.devicePhysicalIds -any _ -eq "[OrderId]:S01")

(device.devicePhysicalIds -any _ -eq "[OrderId]:S01-RM01")

(device.devicePhysicalIds -any _ -eq "[OrderId]:S01-RM01-CRT01")

πŸ” Autopilot Integration: Why It Matters

If you're using Autopilot with Group Tags, this script ensures devices are automatically assigned to the correct:

  • βœ… Dynamic Device Group

  • πŸ“„ Policy

  • πŸ’» App configuration

  • πŸ”’ Compliance baseline

All without ever manually touching the Intune portal.

🎯 Why You Should Use This

  • πŸ•’ Save countless hours of manual work

  • πŸ’Ό Aligns with real-world OU-based environments (schools, branches, departments)

  • πŸ’ͺ Supports zero-touch provisioning and scalable Autopilot deployments

  • πŸ” Fully repeatable and extensible for future growth

βœ… Get the Script

Want the script? Reach out via DM or drop a comment β€” or stay tuned for Part 2, where I’ll show how to chain this with:

  • πŸ”„ An OU Exporter

  • 🎯 A Profile-to-DDG auto assigner

  • πŸ› οΈ A full Autopilot zero-touch toolkit

<#
.Author 
    Ali Alame - CYBERSYSTEM
.SYNOPSIS
    Automates the creation of Intune dynamic device groups from a text file of Active Directory OUs.

.DESCRIPTION
    Reads a list of Active Directory Organizational Units (OUs) from a text file,
    connects to Microsoft Graph, and creates one Azure AD dynamic device group
    per OU. The group name follows the format "AZ-OU-Autopilot-DDG", where "OU"
    is the simple name of the OU. The Intune GroupTag for each created group
    is set to the same simple OU name.

.PARAMETER InputFilePath
    The path to the text file containing a list of Active Directory OUs (one per line).

.NOTES
    Requires the RSAT ActiveDirectory module and the Microsoft.Graph.Authentication
    and Microsoft.Graph.Groups PowerShell modules.
#>
param([Parameter(Mandatory=$true)][string]$InputFilePath)

# ---------- 1. Ensure required modules are present -------------------
$graphSub = @('Microsoft.Graph.Authentication', 'Microsoft.Graph.Groups')
foreach ($m in $graphSub) {
    if (-not (Get-Module -ListAvailable -Name $m)) {
        Write-Host "Installing $m..."
        Install-Module $m -Scope CurrentUser -Force -ErrorAction Stop
    }
}
Import-Module Microsoft.Graph.Authentication, Microsoft.Graph.Groups -Force

# ---------- 2. Read OUs from the input file --------------------------
try {
    $OUsFromFile = Get-Content -Path $InputFilePath -ErrorAction Stop
    if (-not $OUsFromFile) {
        Write-Warning "The input file is empty."
        exit
    }
}
catch {
    Write-Error "Error reading file: $($_.Exception.Message)"
    exit
}

# ---------- 3. Connect to Graph ---------------------------------
try {
    Connect-MgGraph -Scopes 'Group.ReadWrite.All' -ErrorAction Stop
}
catch {
    Write-Error "Error connecting to Microsoft Graph: $($_.Exception.Message)"
    exit
}

# ---------- 4. Process each OU and create Dynamic Device Group -----
foreach ($OU in $OUsFromFile) {
    # Extract the simple OU name (assuming canonical path format)
    $SimpleOUName = ($OU -split '/')[-1]

    # Construct the dynamic group name
    $GroupName = "AZ-$SimpleOUName-Autopilot-DDG"

    # Sanitize the group name for MailNickname
    $MailNickname = $GroupName -replace '[^0-9A-Za-z]', ''

    # Build the dynamic membership rule
    $rule = '(device.devicePhysicalIds -any _ -eq "[OrderID]:' + $SimpleOUName + '")'

    $params = @{
        DisplayName                 = $GroupName
        Description                 = "Dynamic device group for OU: $SimpleOUName"
        MailEnabled                 = $false
        MailNickname                = $MailNickname
        SecurityEnabled             = $true
        GroupTypes                  = @('DynamicMembership')
        MembershipRule              = $rule
        MembershipRuleProcessingState = 'On'
    }

    try {
        New-MgGroup @params -ErrorAction Stop
        Write-Host "[+] Group created: $GroupName"
    }
    catch {
        Write-Warning "[-] Could not create group ${GroupName}: $($_.Exception.Message)"
    }
}

Write-Host 'Completed. Dynamic device group creation process finished.'
Previous
Previous

Dynamic Device Renaming in Intune Using Group Tags and PowerShell