Create Security Group and Add Members in Azure AD using PowerShell

Azure AD Security Groups are Security Principals which can be used to secure objects. In Microsoft 365, we can assign licenses and apply Condition Access policies to users through security groups. In this post, we will explore how to create a new security group and add bulk members from CSV using PowerShell.

Before you start, install the Azure AD PowerShell V2 module and run the below command to connect the Azure AD module.

Connect-AzureAD

Summary

Create a new Security group

We can use the New-AzureADGroup cmdlet to create a new security group. Need to set the SecurityEnabled parameter as $True to make the group as security.

New-AzureADGroup -DisplayName "TestSecurityGroup" -SecurityEnabled $true -Description "Test security group"  -MailEnabled $false -MailNickName "NotSet"

We can’t use this command to create a mail-enabled security group. We need to use Exchange Online PowerShell to create mail-enabled security groups. For more details, see this post: Create and Manage Mail-Enabled Security Groups using PowerShell

We will receive the following error message when we try to create a mail-enabled security group using the New-AzureADGroup cmdlet or Microsoft Graph API.

PS C:\> New-AzureADGroup -DisplayName “Test MSG” -SecurityEnabled $true -MailEnabled $true -MailNickName “testmsg” -Description “Test mail security group”

New-AzureADGroup : Error occurred while executing NewGroup
Code: Request_BadRequest
Message: Cannot Create a mail-enabled security groups and or distribution list.

Once the group is created successfully, you can check the group details by running the below command.

Get-AzureADGroup -SearchString "TestSecurityGroup"

Add Members and Owners to a Security group

We can use the Add-AzureADGroupMember cmdlet to add members to an Azure AD group.

$Group = "TestSecurityGroup"
$User = "[email protected]"
$GroupObj = Get-AzureADGroup -SearchString $Group
$UserObj = Get-AzureADUser -ObjectId $User

Add-AzureADGroupMember -ObjectId $GroupObj.ObjectId -RefObjectId $UserObj.ObjectId

Use the Add-AzureADGroupOwner cmdlet to add users to a group as the owner.

$GroupObj = Get-AzureADGroup -SearchString "TestSecurityGroup"
$UserObj = Get-AzureADUser -ObjectId "[email protected]"

Add-AzureADGroupOwner -ObjectId $GroupObj.ObjectId -RefObjectId $UserObj.ObjectId

Run the below command to display the current members of the security group.

$GroupObj = Get-AzureADGroup -SearchString "TestSecurityGroup"
Get-AzureADGroupMember -ObjectId $GroupObj.ObjectId

Use the below command to get the owners of the security group.

$GroupObj = Get-AzureADGroup -SearchString "TestSecurityGroup"
Get-AzureADGroupOwner -ObjectId $GroupObj.ObjectId

Add Bulk Members to a Security Group from CSV

Consider the CSV file “GroupMembers.csv” (Download sample CSV) that includes the column header “UserPrincipalName” which holds the user identity values in each row of the CSV file. Run the below script to add members in bulk to a security group by importing users from the given CSV file.

$Group = "TestSecurityGroup"
$GroupObj = Get-AzureADGroup -SearchString $Group

#Read group members from CSV file
$GroupMembers = Import-CSV "C:\Temp\GroupMembers.csv"

#Iterate members one by one and add to group
Foreach($GroupMember in $GroupMembers)
{
$User = $GroupMember."UserPrincipalName"
Write-Progress -Activity "Adding member" -Status $User
Try
{
$UserObj = Get-AzureADUser -ObjectId $User
Add-AzureADGroupMember -ObjectId $GroupObj.ObjectId -RefObjectId $UserObj.ObjectId
}
catch
{
Write-Host "Error occurred for $User" -f Yellow
Write-Host $_ -f Red
}
}

Create Bulk Security Groups from CSV and Add Members

Consider the CSV file “SecurityGroups.csv” (Download sample CSV) that includes the column headers ‘GroupName’, ‘GroupDescription’, ‘Owners’, ‘Members‘. The CSV file holds the security group details (name and description) and owners/members as semi-colon-separated (;) values in each row of the CSV file. Run the following script to create security groups and add owners and members in bulk by importing details from the given CSV file.

#Read security group details from CSV file
$CSVRecords = Import-CSV "C:\Temp\SecurityGroups.csv"
$TotalItems = $CSVRecords.Count
$i = 0
 
#Iterate groups one by one and create
ForEach($CSVRecord in $CSVRecords)
{
$GroupName = $CSVRecord."GroupName"
$GroupDescription = $CSVRecord."GroupDescription"
#Split owners and members by semi-colon separator (;) and set in array
$Owners = If($CSVRecord."Owners"){ $CSVRecord."Owners" -split ';' } Else { $null }
$Members = If($CSVRecord."Members"){ $CSVRecord."Members" -split ';' } Else { $null }

Try
{
$i++;
Write-Progress -Activity "Creating group $GroupName" -Status  "$i out of $TotalItems groups completed" -Id 1

#Create a new security group
$NewGroupObj = New-AzureADGroup -DisplayName $GroupName -SecurityEnabled $true -Description $GroupDescription  -MailEnabled $false -MailNickName "NotSet" -ErrorAction Stop

#Add owners
if($Owners)
{
$TotalOwners = $Owners.Count
$OW = 0
ForEach($Owner in $Owners)
{
$OW++
Write-Progress -Activity "Adding owner $Owner" -Status  "$OW out of $TotalOwners owners completed" -ParentId 1
Try
{
$UserObj = Get-AzureADUser -ObjectId $Owner -ErrorAction Stop
#Add owner to the new group
Add-AzureADGroupOwner -ObjectId $NewGroupObj.ObjectId -RefObjectId $UserObj.ObjectId -ErrorAction Stop
}
catch
{
Write-Host "Error occurred for $Owner" -f Yellow
Write-Host $_ -f Red
}
}
}
#Add members 
if($Members)
{
$TotalMembers = $Members.Count
$m = 0
ForEach($Member in $Members)
{
$m++;
Write-Progress -Activity "Adding member $Member" -Status  "$m out of $TotalMembers members completed" -ParentId 1
Try
{
$UserObj = Get-AzureADUser -ObjectId $Member -ErrorAction Stop
#Add a member to the new group
Add-AzureADGroupMember -ObjectId $NewGroupObj.ObjectId -RefObjectId $UserObj.ObjectId -ErrorAction Stop
}
catch
{
Write-Host "Error occurred for $Member" -f Yellow
Write-Host $_ -f Red
}
}
}
}
catch
{
Write-Host "Error occurred while creating group: $GroupName" -f Yellow
Write-Host $_ -f Red
}
}
Advertisement

15 thoughts on “Create Security Group and Add Members in Azure AD using PowerShell”

  1. please help me solving this issue:
    PS C:\WINDOWS\system32> $GroupObj = Get-AzureADGroup -SearchString $SecurityGroupName
    $UserObj = Get-AzureADUser -SearchString $SecurityGroupOwner
    Add-AzureADGroupMember -ObjectId $GroupObj.ObjectId -RefObjectId $UserObj.ObjectId

    Add-AzureADGroupMember : Cannot bind argument to parameter ‘RefObjectId’ because it is null.
    At line:3 char:66
    + … oupMember -ObjectId $GroupObj.ObjectId -RefObjectId $UserObj.ObjectId
    + ~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Add-AzureADGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Open.AzureAD16.PowerShell.AddGroupMember

    Reply
    • The error message indicates that the user (member) object ($UserObj) is null.

      $User = “[email protected]
      $UserObj = Get-AzureADUser -SearchString $User

      Run the following command after replacing your user’s UPN to ensure the user exists or not

      Get-AzureADUser -SearchString “[email protected]

      Reply
  2. Cannot bind argument to parameter ‘RefObjectId’ because it is null.

    This worked

    I changed
    from : $UserObj = Get-AzureADUser -SearchString $User

    to : $UserObj = Get-AzureADUser -ObjectId $User

    Reply
  3. @morgan

    I get this Error while Adding Bulk Members to a Security Group from CSV ..,Please help

    Import-CSV : The member “UserPrincipalName” is already present.
    At line:5 char:17
    + $GroupMembers = Import-CSV “C:\Temp\DDD.csv”
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Import-Csv], ExtendedTypeSystemException
    + FullyQualifiedErrorId : AlreadyPresentPSMemberInfoInternalCollectionAdd,Microsoft.PowerShell.Commands.ImportCsvCommand

    Reply
    • The error message indicates that you have two columns with the same name (“UserPrincipalName”) in the “DDD.csv” file. Remove the duplicate column and try again.

      Reply
    • Pls, use the below line. Use MemberId instead of RefObjectId.

      Remove-AzureADGroupMember -ObjectId $GroupObj.ObjectId -MemberId $UserObj.ObjectId

      Reply
  4. Newbie here:
    If I add 2 columns for dates (AddDate and RemovalDate) and check if the date matches AddDate then add the user to the group and if matches RemovalDate then remove user from group?

    Reply
  5. Adding users in few AD DL group via CSV

    $csv = Import-CSV “C:\Users\XXXX\TeamsVoiceUser.csv”

    #Iterate members one by one and add to group
    ForEach($csv in $csv)
    {
    $Group = $csv.”GroupName”
    $User = $csv.”email”
    Write-Progress -Activity “Adding member” -Status $User
    Try
    {
    $UserObj = Get-AzureADUser -ObjectId $User
    Add-AzureADGroupMember -ObjectId $GroupObj.ObjectId -RefObjectId $UserObj.ObjectId
    }
    catch
    {
    Write-Host “Error occurred for $User” -f Yellow
    Write-Host $_ -f Red
    }
    }

    Reply

Leave a Comment