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
}
}
}
Hello there,
Script seems to work but the AAD group does not seem to populate.
Still hard to believe MS don’t have an easier way to multiple upload devices to a 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…..
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}
Nice find, thanks for updating me 🙂
Jimmy I had issue with this piece of code ->
$refid = Get-AzureADDevice -Filter “DisplayName eq ‘$machine’”
The single quotation have me this error -> Get-AzureADDevice : Error occurred while executing GetDevices
Code: Request_BadRequest
Message: Syntax error: character ‘‘’ is not valid at position 15 in ‘DisplayName eq ‘LAP5”.
Changing the quotation mark resolved
$machines = get-content C:\bot\Book2.csv
$refid = Get-AzureADDevice -Filter “DisplayName eq ‘$machine’”
That is likely a copy-paste formatting issue, WordPress sometimes using funny fonts for quote characters :/
Like Avean above the script doesn’t work for me either. Just tells me Computer object is already a member. Hopefully you can get it to work Jimmy as it would be really useful.
Have you checked to see if there are multiple objects (stale records) in Azure AD?
Also, take a look at https://gitlab.com/Lieben/assortedFunctions/blob/master/disable-duplicateAzureAdDevices.ps1
If you have many duplicate devices, this could help
Like Avean and Christian above the script doesn’t work for me either. Just tells me Computer object is already a member. and i checked these devices do not have duplicate entries.
Ok, can you provide any anonymous details and I’ll take a look. Are you running hybrid/azure only etc. any details you think may help
these deices are managed by Intune and Azure AD joined; Hybird
Looks like the script didn’t work for me as well.
I am the same, devices managed by Intune. The devices are Azure AD joined and Hybrid.
Was there a solution to this?
I’ll be honest, I haven’t had time to dig into yet, it still works for me. Have you checked for orphaned/duplicate devices in Azure AD?
I put a sample size of 10 devices. each device only had 2 records. one hybrid and the other azure ad joined.
unfortunately none of them added
Ok, I’ll try and look at it today see if I can replicate the issue
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
It is as if the condition needs to have a group that has devices in there already.
If you start off as a new group it’s always blank and skips straight to “device is already a member”
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 🙂
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!
Just testing now. I suspect the $false on line 66 should be $true
Found a logic error and updated, please try it now