We’re gonna use, Microsoft.Office.Server.UserProfiles.UserProfileManager class to get a given Microsoft.Office.Server.UserProfiles.UserProfile and update some of its values. Say, there are two custom properties defined in the SharePoint Central Admin which are mapped to some TermStores. They are:
- CpSingle [Single metaData value is allowed. Mapped to say Continent/Region].
- CpMulti [This metaData field can have multiple values. Mapped to say Countries.].
Our objective is to update these metadata fields using a powerShell script. Before we delve into that, there are few things that needs to be clarified here.
- Indexing a userProfile object, say, $userProfile[“CpSingle”], will return an object of Microsoft.Office.Server.UserProfiles.UserProfileValueCollection.
- So we can add multiple values to this object using its Add(Object o) function.
- Similarly, existing items can be removed by calling its Clear() function.
- If only a single property has to be set then, we can use it’s Value property to do the same. It gets or sets the value of the profile property.
So here’s the script snippet.
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server") [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") #Get any site $site = Get-SPSite -Limit 1 $context = Get-SPServiceContext($site) $profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context) $userProfile = $profileManager.GetUserProfile("domain\UserName") #Some default properties can be accessed using the dot operator. Write-Host ("Changing custom properties for " + $userProfile.DisplayName) #valid region value $userProfile["CpSingle"].Value = "Asia" #First clear any existing item for multi property. Then add our values. $userProfile["CpMulti"].Clear() $userProfile["CpMulti"].Add("India") $userProfile["CpMulti"].Add("Bhutan") $userProfile["CpMulti"].Add("Sri Lanka") #Finally save all the changes. $userProfile.Commit()
This script is good for modifying the custom metadata properties of a single user. But if we want to make these changes or some other changes uniform to all the existing UserProfiles, then we need to enumerate through all the userProfiles instead of fetching a single value. Same script to update the above mentioned custom properties with the same value for all the UserProfiles is mentioned below.
$profiles = $profileManager.GetEnumerator() while ($profiles.MoveNext()) { #Get the current profile $userProfile = $profiles.Current Write-Host ("Changing custom properties for " + $userProfile.DisplayName) #valid region value $userProfile["CpSingle"].Value = "Asia" #First clear any existing item. Then add our values. $userProfile["CpMulti"].Clear() $userProfile["CpMulti"].Add("India") $userProfile["CpMulti"].Add("Bhutan") $userProfile["CpMulti"].Add("Sri Lanka") #Finally save all the changes. $userProfile.Commit() }