Bulk add devices to Azure AD Group

A simple script, which takes a list of device names in a text file and adds them to the specified Azure AD group.

Requires the AzureAD PowerShell module, the script will check for its existence and offer to install it if it is not found. This script can cope with MFA for Azure AD admins.

*UPDATE – Now copes with Multiple entries for same machine (Stale records). Caveat: It adds the stale record as well – If you are seeing duplicates being added, you have stale records and should consider tidying up your Azure AD

 
<#
.Synopsis
   Add Computers to Azure AD Group
.DESCRIPTION
   Add Computers to Azure AD Group. Jimmy White Feb 2021 www.deviousweb.com
.EXAMPLE
  Create a txt file with the netbios names of devices you want to add. The script invokes a file picker to allow you to choose the file.
.INPUTS
   Inputs to this cmdlet (if any) None
.OUTPUTS
   Output from this cmdlet (if any) Console
.NOTES
   General notes
.COMPONENT
   AzureAD

#>
###################################################################################
#                       Adjust these variables accordingly...                     #
###################################################################################
$azgroup = "sg-appdeploy-win-mcafee-agent"

###################################################################################

#lets check to see if we have the Azure AD module installed...

if (Get-Module -ListAvailable -Name Azuread) {
    Write-Host "AzureAD Module exists, loading"
	Import-Module Azuread 
	} 
else {
    #no module, does user hae admin rights?
    Write-Host "AzureAD Module does not exist please install`r`n with install-module azuread" -ForegroundColor Red
	
		if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
		[Security.Principal.WindowsBuiltInRole] "Administrator")) {
			Write-Host "Insufficient permissions to install module. Please run as an administrator and try again." -ForegroundColor DarkYellow
            return(0)
		    }
		else {
		    Write-Host "Attempting to install Azure AD module" -ForegroundColor Cyan
		    Install-Module AzureAD -Confirm:$False -Force
        }
	
}

# OK, lets pick the file..
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{ 
    InitialDirectory = [Environment]::GetFolderPath('Desktop') 
    Filter = 'Documents (*.txt)|*.txt|TextFile (*.txt)|*.txt'
}
$null = $FileBrowser.ShowDialog()
$machines = get-content $FileBrowser.FileName


#ok, if we got here, we must have the Azure AD module installed, lets connect...
Connect-AzureAD
write-host "Getting Object ID of group.." -ForegroundColor Green
$objid = (get-azureadgroup -Filter "DisplayName eq '$azgroup'" ).objectid
write-host "Getting group members (We dont want duplicates!).." -ForegroundColor Cyan
$members = Get-AzureADGroupMember -ObjectId $objid -all $true | select displayname

foreach ($machine in $machines) {


    $refid = Get-AzureADDevice -Filter "DisplayName eq '$machine'" 
    ############################################
    foreach($ref in $refid){ #just in case there are stale AZ AD objects throwing multiple matches!
    $result = $null
    $result =  ($members -match $machine) #is it already in the group?
    if(!$result){
        try{
            Write-host "Adding " $ref.displayname -ForegroundColor Cyan
            Add-AzureADGroupMember -ObjectId $objid -RefObjectId $ref.objectid
            }
        catch{
            write-host "An error occured for " $ref.displayname  -ForegroundColor Red
            }
        }
        else
        {
            write-host $machine " is already a member" -ForegroundColor Green
        }
    }
}

22 thoughts on “Bulk add devices to Azure AD Group”

    • Experienced the same. First time i run the script it said “is already a member” which it isnt since its an empty group and the group is specified correctly. Then i ran the script again and it said “Member already added” but two hours later this group is still empty…..

  1. OK, thanks to my colleague who is more PS aware than myself we found the problem. The objects were not uploading to the AAD group because we had multiple duplicate AZ Id’s for many of the pc’s – some stale records still in AAD.

    My colleague added the following to weed out any duplicate stale records for the objects:

    foreach ($machine in $machines) {
    $refid = Get-AzureADDevice -Filter “DisplayName eq ‘$machine'” | Where {$_.IsCompliant -eq $False}

      • So I was playing around with your code more. I think I see the problem. Some logic issue with your
        ($members – match $machine)

        It always passes in blank. I got your code to work by having devices in the group to begin with. That will explain the set of users in this post saying it worked.

        But for anyone that starts off as an empty group, it will fail

          • That’s is supposed to be be blank, it checks to see if the machine is already a member,
            the next line:
            if($result -eq “”){
            is where it picks up the blank then adds it to the group..

            Ill continue looking at it today 🙂

  2. yup. your login makes sense! chucked in some write-host statements and things seems to pass in correctly.
    I can’t seem to figure it out. maybe instead of blank it needs a $null?
    try replicating it and add it to an empty group!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.