Search code examples
azure-active-directoryazure-powershell

Bulk adding users to AzureAD Script error


The goal of the script is to run and add all users with a specific job title to an AzureAD Group. I've tested the variable and it grab the right people and will display if I write the variable to the screen.

The error message I get states "ADD-AzureADGroupMember : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter.

#Grab all users with the job title IT Support Technician
$User = (Get-AzureADUser -All $true | 
Where-Object -FilterScript {$_.JobTitle -eq "IT Support Technician"}).ObjectId

#Grab the ObjectID of the AzureADGroup
$Branch = (Get-AzureADGroup -SearchString "Test SG").ObjectId

#Add each of the Users to the AzureADGroup
$User | ForEach-Object {
Add-AzureADGroupMember -ObjectId $Branch -RefObjectId $User
}

Solution

  • You're iterating over $user then trying to add all users within your Foreach-Object loop.

    To reference the current pipeline item you can use $_ or $PSItem

    $User | ForEach-Object {
        Add-AzureADGroupMember -ObjectId $Branch -RefObjectId $_
    }
    

    Documentation on Automatic Variables

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.2#_