PowerShell Script to add users to Entra ID Security Group while not processing users already in the group - using MS Graph PowerShell

mark terry 85 Reputation points
2025-01-14T01:13:33.0633333+00:00

Hi folks!

I have the following CSV File:

userprincipalname

user1@test.com

user2@test.com

I would like to able to use Microsoft Graph PowerShell to read the contents of this file so each member of the file is added to an Entra ID Security Group. I would like to do this using the new Graph cmdlets (e.g. New-MgGroupMember) and not the older Add-AzureADGroupMember cmdlet.

I would also like the script to bypass any users who are already in the Group. The existing script I have (see below) is using the old AzureAD PowerShell Module. I basically want to update this to use the new Graph PowerShell.

Thanks!

$GroupName = "Test User Group"
$CSVFile = "D:\Temp\Users.csv"
 
#Get users to import from a CSV File
$Users = Import-Csv -Path $CSVFile
 
#Connect to Azure AD
Connect-AzureAD
 
#Get the Group
$Group = Get-AzureADGroup -Filter "SecurityEnabled eq true and MailEnabled eq false and Displayname eq '$GroupName'"
 
#Get Exisiting Members of the Group
$GroupMembers = Get-AzureADGroupMember -ObjectId $Group.ObjectId -All $true | Select -ExpandProperty UserPrincipalName
 
#Add Each user to the Security group
ForEach ($User in $Users)
{
    #Check if the group has the member already
    If($GroupMembers -contains $User.UserPrincipalName)
    {
        Write-host "User '$($User.UserPrincipalName)' is already a Member of the Group!" -f Yellow
    }
    Else
    {
        $UserObj = Get-AzureADUser -ObjectId $User.UserPrincipalName
        Add-AzureADGroupMember -ObjectId $Group.ObjectId -RefObjectId $UserObj.ObjectId
        Write-host "User '$($User.UserPrincipalName)' has been added to the Group!"
    }
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,600 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,856 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Andy David - MVP 151.1K Reputation points MVP
    2025-01-14T12:38:39.3266667+00:00

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.