PowerShell Script – Add Device to Entra ID Group from CSV File

This PowerShell script adds devices to an Entra ID group via a CSV file, streamlining device management. It reads a CSV containing device details, authenticates to Entra ID, and processes each entry, assigning devices to the specified group.

For an Intune admin, this script eliminates manual data entry, reducing errors and saving valuable time. It ensures consistency in device grouping, enhances policy enforcement, and simplifies large-scale deployments. By automating routine tasks, admins can focus on strategic IT initiatives rather than tedious administrative work.

The device name should be provided in the CSV file in the following format.

PowerShell script - Add device to Entra ID group

Use the PowerShell script to add the device to an Entra ID group. You should place the devices.csv file in the script folder itself.


$csvFilePath = "$PSScriptRoot\devices.csv"
$groupName = "Test-Group"

#Install Microsoft.Graph.Intune module
if(-not (Get-Module Microsoft.Graph.Intune -ListAvailable))
{
    Write-Host "Installing Microsoft.Graph Intune Module" -ForegroundColor Cyan
    Install-Module Microsoft.Graph.Intune -Scope CurrentUser -Force
}


Connect-AzureAD
Connect-MgGraph
 
$devices = Import-Csv -Path $csvFilePath

$group = Get-AzureADGroup -SearchString $groupName
$groupId = $group.objectID

$totalDevices = ($devices).Count 
$sn=1 

Write-Host "Total Devices: $totalDevices" -ForegroundColor Yellow

 
foreach ($device in $devices) {

 try 
   { 

    $deviceName = $device.DeviceName

    $deviceInfo = Get-mgDevice -Filter "displayName eq '$deviceName'" |select-object id

    $deviceGUID = $deviceInfo.Id

    Write-Host -NoNewline "Device:$sn of $totalDevices,Device Name: $deviceName, ObjectID: $deviceGUID, Group Name: $groupName, ObjectID: $groupId,Status:" -ForegroundColor Cyan
    
    Add-AzureADGroupMember -ObjectId $groupId -RefObjectId $deviceGUID
    Write-host "Success" -ForegroundColor Green
   
   }

    catch 
       { 

        $message = $_.Exception.Message 
        Write-Host  "Error: $message" -ForegroundColor Red 
       } 

   $sn+=1 
      
}

PowerShell script - Add device to Entra ID group

Related Posts

Subscribe to Techuisitive Newsletter

Be the first to know about our new blog posts. Get our newsletters directly in your inbox and stay up to date about Modern Desktop Management technologies & news.

Scroll to Top