Powershell to create user AND update Work E-mail in User Profile

Brass Contributor

Hello, 

I am trying to build a powershell script that will run against SharePoint Online.  It will create a new user, and update their Work-Email property in their SharePoint Online User Profile.

The script already successfully creates a user, usign the New-MsolUser command.

It then attempts to set the Work E-mail property by using the command:

Set-SPOUserProfileProperty -Account $userprincipalname -PropertyName "Workemail" -Value $NewUserEmail 

This comes back with the error:

User Profile Error 1000: User Not Found: Could not load profile data from the database.

When I login to a SharePoint site using the new account, I am then able to use the above command to update the profile. How can I get the Use Profile created during my script execution so that I can update the property?

5 Replies
What you need to take into account is that you first have created the user in Azure AD and the object that is created behind the scenes is propagated first to SPO DS (that's why you are able to use the user on a team site) what does not mean the same happens with user profiles...you need to wait until the new profile is available there (sorry but I don't recall now the schedule for user profiles in SPO)

Hmm... I'm not sure that it's "scheduled." It always works once I've logged in, which tells me there's a way to trigger it. Also, I've waited over a weekend once, and the profile was still not available.

You will need to add the user to a site:

 

New-SPOUser -LoginName "username@tenant.onmicrosoft.com"

 

and then

 

New-SPOPersonalSite -Email "username@tenant.onmicrosoft.com"

 

This will then create your user prorfile after a while and then you can update your properties.

 

 

 

 

In order to make the profile available in SPO the user need to access the shared files in that site. Alternately you can use the cmd Add-SPOUser to add the user in any of the sites and then run your command. HTH.

I did complete this, but I'm not happy with how it works. First, as background, the users I'm creating in this case are also added to Azure AD Groups that have access to SharePoint Online, so it may be that SharePoint is creating user profiles for them as a result of this. Still, I have to wait for SPOnline to do this. I tried the "New-SPOUser" command line to no avail.
I essentially have a "While" loop that tries to modify the property, and catches the error if it occurs so that it can try again in 30 seconds:

$test = 1
While ($test -eq 1)
{
 Try {
  Write-Host "Trying to set property"
  Set-SPOUserProfileProperty -Account $userprincipalname -PropertyName   "Workemail" -Value $NewUserEmail -ErrorAction Stop
  $test = 0
  $curTime = Get-Date
 } Catch {
  $badTime = Get-Date
  Write-Host $_.Exception.Message -ForegroundColor Red
  Write-Host "Didn't work at $badTime, trying again in 30 seconds. This   usually takes up to 30 minutes."
  Start-Sleep -Seconds 30
 }
}