Reputation: 25
I'm using a Powershell script to add new users to O365 and assign multiple licenses. However i'm now trying to also add the new user to existing groups.
Powershell
Connect-MsolService -Credential $UserCredential
Import-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuIdEMS,$_.AccountSkuIdENTERPRISEPACK} | Export-Csv -Path "C:\Users\Jesse\Documents\Powershell\NewAccountResults.csv" -Verbose
.CSV
DisplayName,FirstName,LastName,UserPrincipalName,Usagelocation,AccountSkuIdEMS, AccountSkuIdENTERPRISEPACK
Test Jesse,Test,Jesse,test.jesse@(Tenant).nl,NL,(Tenant):EMS,(Tenant):ENTERPRISEPACK
I've found the following code, but wouldn't know how to correctly implement it into my existing code. I think i would also need to connect to a new service to use this cmdlet. is it possible to switch between connections within a single script?
Add-UnifiedGroupLinks -Identity "Azure AD Join" -LinkType Members -Links test.jesse@(tenant).nl
Upvotes: 0
Views: 298
Reputation: 16438
You could use AzureAD Module cmd Add-AzureADGroupMember to add the new user to existing groups.
Remember to install AzureAD Module by following Azure Active Directory PowerShell for Graph.
You can reuse the $Credential
for AzureAD Module in Powershell. It won't require you to login again.
Here is my sample for your reference:
$Credential = Get-Credential
Connect-MsolService -Credential $Credential
Import-Csv -Path "E:\test\NewAccounts.csv" | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation} | Export-Csv -Path "E:\test\NewAccountResults.csv"
Connect-AzureAD -Credential $Credential
$newusers = Import-Csv -Path "E:\test\NewAccounts.csv" | foreach {Get-AzureADUser -Filter "userPrincipalName eq '$($_.UserPrincipalName)'"}
foreach ($user in $newusers){
Add-AzureADGroupMember -ObjectId "{object id of the existing group}" -RefObjectId $user.ObjectId
}
BTW, you can get the object id of the existing group from Azure portal.
Upvotes: 1