Wednesday, 30 October 2013

A Quick Guide to Getting, Setting and Copying User Profile Properties using PowerShell

Whether you're a SharePoint Administrator or SharePoint Developer, being able to quickly read, update or copy User Profile properties is a handy skill to have. Using PowerShell to get and set User Profile properties is both quick and easy. This post outlines how to do it!

Getting the User Profile


The basic PowerShell code for getting a user profile, using a users UPN (User Principal Name):
[void][reflection.assembly]::Loadwithpartialname("Microsoft.Office.Server") | out-null;            
$site=new-object Microsoft.SharePoint.SPSite("https://c05470sp10:7443");            
$serviceContext = Get-SPServiceContext $site;            
$site.Dispose();            
$upm = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);            
$userProfile = $upm.GetUserProfile("myarlett@company.com");



The basic PowerShell code for getting a user profile, using the user's login name:
[void][reflection.assembly]::Loadwithpartialname("Microsoft.Office.Server") | out-null;            
$site=new-object Microsoft.SharePoint.SPSite("https://c05470sp10:7443");            
$serviceContext = Get-SPServiceContext $site;            
$site.Dispose();            
$upm = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);
$userProfile = $upm.GetUserProfile("company\myarlett");


Listing all the Profile Fields (Properties) and their Types


List the user profile properties (including the field type). This is handy, because we'll need to know what the field type is before trying to set it's value:
$userProfile.Properties | sort DisplayName | FT DisplayName,Name,@{Label="Type";Expression={$_.CoreProperty.Type}}



Getting the Value of a Property

Get the users About Me property (HTML):
$userProfile["AboutMe"].Value


Setting the Values of Properties


Update the users Location (String field):
$userProfile["SPS-Location"].Value = "London";            
$userProfile.Commit();

Update the users Manager (Person field):
$userProfile["Manager"].Value = (Get-SPWeb https://c05470sp10:7443).EnsureUser("company\fred");
$userProfile.Commit();

Note that in the above example, we have retrieved an SPUser object (for the manager) from the Central Admin site, using the EnsureUser method.

Copying User Profile Properties between Profiles


Copy fields from one user profile to another:
$userProfile2 = $upm.GetUserProfile("company\matthewette");            
$userProfile2["AboutMe"].Value = $userProfile["AboutMe"];            
$userProfile2.Commit();

See Also




No comments:

Post a Comment