PowerShell script to add devices to Azure AD group with and without Object IDs

Published on

in

,

In this blog we are going to see how we can add Azure AD joined devices to an AAD group using and without using Object IDs with PowerShell. I came across this scenario while I was working as an IT Pro.

Table of Contents:

Pre-requisites

  1. The first and foremost pre-requisite you need to have installed on your machine is the PowerShell Az module.
    You can install the Az PowerShell module with one of the following methods:
    i. Install the Az PowerShell module via PowerShellGet (recommended option).
    ii. Install the Az PowerShell module with MSI.
    For more information on Azure Az PowerShell module, please visit Microsoft Documentation.
  2. You must have Write permission on the Azure AD groups where you are going to add the devices.

Scenarios

Scenario 1: You have the Azure AD Object IDs for the devices.
In this case, we can directly make use of the Add-AzureADGroupMember cmdlet that adds a member to a group.

Add-AzureADGroupMember -ObjectId "62438306-7c37-4638-a72d-0ee8d9217680" -RefObjectId "0a1068c0-dbb6-4537-9db3-b48f3e31dd76"

For more information on Add-AzureADGroupMember, please visit this link.

Scenario 2: You do not have their AAD Object IDs. Instead you have the device Names and their Azure AD Device IDs. In this case, we will first try to get the Object IDs for each device so that we can use Add-AzureADGroupMember cmdlet.
To proceed, let’s create a csv file named DevicesToAdd.csv which have two columns with headers in the below format:

DeviceName,azureADDeviceId
james-laptop,2bb27401-6b71-4c43-8b1d-ccd81e4f6623
James-surface,46d6c1fe-c099-420a-994e-d3f0db447983

Copy the below script:

$groupName = "myAADGroupName"
try {
    $deviceList = Import-Csv -Path "D:\DevicesToAdd.csv"
    Connect-AzureAD
    $groupObj = Get-AzureADGroup -SearchString $groupName
    foreach ($device in $deviceList) {
        $deviceObj = Get-AzureADDevice -SearchString $device.DeviceName
        if($deviceObj -ne $null){
            try{
                foreach($dev in $deviceObj){
                    if($dev.DeviceId -eq $device.azureADDeviceId){
                        Add-AzureADGroupMember -ObjectId $groupObj.ObjectId -RefObjectId $dev.ObjectId       
                    }
                }   
            }
            catch{}
        }
        else{
           Write-Host "No device found:$($device.DeviceName)"
        }
    }
}
catch {
    Write-Host -Message $_
}

Script explanation:
i. The script creates a variable $groupName which stores the AAD group name.
ii. The variable $deviceList contains all the devices from the csv file.
iii. Connect-AzureAD connects you to the Azure Active Directory
iv. It gets the details of the group so that its object ID can be used later.
v. For each device in the list, the script calls the Get-AzureADDevice cmdlet to get the device details. However, duplicate device names or display names can exist. So, it checks for the specific device in your list by comparing the device ID.
vi. Upon successful comparison, the right device is added to the group using its ObjectID with the help of Add-AzureADGroupMember cmdlet.

Hope this helped you a bit. Thank you and stay tuned.

3 responses to “PowerShell script to add devices to Azure AD group with and without Object IDs”

  1.  Avatar
    Anonymous

    Grate script it solved my requirement, but it is not giving output of added workstation, what changes required in the script for that.

    Like

  2.  Avatar
    Anonymous

    AzureAD is deprecated, could you please update the script using Microsoft Graph PowerShell SDK modules?

    I am trying to automate the Intune device adding to a specific exclusion group while installing a Win32 app.

    Currently on devices we have O365 apps installed as 32Bit & I have deployed 64bit app with ODT tool & deployed as Win32.

    While the current device is also part of 32bit assignment, I have create another 64bit group & assigned it to exclusion.

    While user install the 64bit app from Company Portal, the device needs to get automatically added to 64bit app group, any suggestions on this please?

    Like

    1. James Yumnam Avatar
      James Yumnam

      Hi There, thank you for reaching out. I would like to say that it’s been quite sometime that I had left this domain and might not be able to help you with exactly what you are looking for. I am sure it is is just a matter of couple of if else conditions.
      As for the script is concerned, the following updated might help you get started with the Microsoft Graph PS module. It has not been tested as i do not have the subscription as well. Hope this helps you.

      $groupName = “myAADGroupName”

      try {
      $deviceList = Import-Csv -Path “D:\DevicesToAdd.csv”

      # Connect to Microsoft Graph
      Connect-MgGraph -Scopes "Group.ReadWrite.All", "Directory.Read.All"
      
      # Get the group object
      $groupObj = Get-MgGroup -Filter "displayName eq '$groupName'" -ConsistencyLevel eventual
      if ($groupObj -eq $null) {
          Write-Host "Group not found: $groupName"
          return
      }
      
      foreach ($device in $deviceList) {
          # Find the device
          $deviceObj = Get-MgDevice -Filter "displayName eq '$($device.DeviceName)'" -ConsistencyLevel eventual
          if ($deviceObj -ne $null) {
              try {
                  foreach ($dev in $deviceObj) {
                      if ($dev.Id -eq $device.azureADDeviceId) {
                          # Add device to group
                          New-MgGroupMember -GroupId $groupObj.Id -DirectoryObjectId $dev.Id
                      }
                  }
              }
              catch {
                  Write-Host "Error adding device: $($_.Exception.Message)"
              }
          }
          else {
              Write-Host "No device found: $($device.DeviceName)"
          }
      }
      

      }
      catch {
      Write-Host “Error: $($_.Exception.Message)”
      }

      Updates made:
      Install the module: Install-Module -Name Microsoft.Graph -Scope CurrentUser
      Ensure the app or user account running the script has sufficient permissions (Group.ReadWrite.All, Directory.Read.All).

      Connect-MgGraph: Replaces Connect-AzureAD. You must specify the required scopes, such as Group.ReadWrite.All and Directory.Read.All.

      Get-MgGroup: Replaces Get-AzureADGroup. Microsoft Graph requires a filter for search, and it uses -Filter instead of -SearchString.

      Get-MgDevice: Replaces Get-AzureADDevice. It uses a filter query to find devices by their displayName.

      New-MgGroupMember: Replaces Add-AzureADGroupMember. You need to pass the DirectoryObjectId of the member to add to the group.

      Like

Leave a comment