I’m running a script to add a new user to Azure AD
$AzureADConnection = Connect-AzureAD
$AdminEmail = $AzureADConnection.Account.Id
Connect-ExchangeOnline -UserPrincipalName $AdminEmail -ShowProgress $false
$ADUserParameters = @{
DisplayName = $DisplayName
GivenName = $FirstName
SurName = $LastName
UserPrincipalName = $UserPrincipalName
MailNickName = $MailNickName
UsageLocation = $UsageLocation
CompanyName = $CompanyName
JobTitle = $JobTitle
Department = $Department
PasswordProfile = $PasswordProfile
AccountEnabled = $true
}
$NewAzureADUser = New-AzureADUser @ADUserParameters -ErrorAction Stop
The user is created successfully, however, when I run the command to add a user to the Distribution list in the same process, I get an error that the user is not found
$dl = "[email protected]"
Add-DistributionGroupMember -Identity $dl -Member $UserPrincipalName
Couldn’t find object "[email protected]". Please make sure that it was spelled correctly or specify a different
object.
+ CategoryInfo : NotSpecified: (:) [Add-DistributionGroupMember], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : TimeStamp=8/9/202
2 11:55:40 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] D103D115,Microsoft.Exchange.Management.R
ecipientTasks.AddDistributionGroupMember
+ PSComputerName : outlook.office365.com
At the same time, if I run the command after creating a user, then everything works. Can someone please suggest how to solve this problem?
2
Answers
thanks M R Rukmini! I have slightly modified your script and it turned out what I need
I tried in my environment and got the same error as below:
Response:
Please note that, the error usually occurs if the creation of Azure Ad user is still in progress when you tried to add it to Distribution list.
To resolve the error, you can wait for 2-3 mins before executing
Add-DistributionGroupMember
command or you can pause the code by adding sleep like below:When I tried to add the member after few minutes of user creation, user got added successfully to the Distribution list like below:
Reference:
Creating and adding new users to distribution list in Azure by Shelly3360