azureazure-active-directoryazure-powershellazure-ad-powershell-v2

Updating Multiple Users to ADGroup


I'm trying to update AzureADGroupMember for multiple users in a CSV File by UPN.

This is what I've came across and attempted:

$users = Import-csv "C:\Temp\testgroup2.csv" 

$users | ForEach-Object{
Add-AzureGroupADGroupMember -ObjectId xcv9890-stest999-xcvxc234-xcv2342324 
-RefObjectId (Get-AzureADUser -ObjectId $_.UPN).ObjectId
}

I get the following 2 errors.

Import-csv : The member "Role" is already present.
At line:1 char:10

Get-AzureADUser : Cannot bind argument to parameter 'ObjectId' because it 
is null.
At line:4 char:120

Any idea why this keeps happening? I would really appreciate the help.

Thank you,


Solution

  • Well, since you did not provide the .csv file, I can just give you a solution that works on my side.

    First, let's check the two errors.

    Import-csv : The member "Role" is already present.

    I can reproduce this issue, this means your .csv file has two columns header 'Role', just modify it into a correct format.

    enter image description here

    enter image description here

    Get-AzureADUser : Cannot bind argument to parameter 'ObjectId' because it is null.

    This means this part $_.UPN is null, this may be caused by the first error.

    My sample:

    testgroup.csv

    UPN,Role
    leeliu@xxxxxx.onmicrosoft.com,role1
    test@xxxxxx.onmicrosoft.com,role2
    

    enter image description here

    script (you should use Add-AzureADGroupMember, not Add-AzureGroupADGroupMember):

    $users = Import-csv "C:\Users\joyw\Desktop\testgroup.csv" 
    
    $users | ForEach-Object{
    Add-AzureADGroupMember -ObjectId 9d42xxxxxx28b600ad -RefObjectId (Get-AzureADUser -ObjectId $_.UPN).ObjectId
    }
    

    Note: Before running the script, you need to make sure the users are not already in the group, otherwise you will get a One or more added object references already exist for the following modified properties: 'members' error.