SharePoint People Picker Columns (via Powershell)

With a SharePoint list, the “People Picker” column can be a little tricky to deal with – as it’s an “object” – not just a string value.

A colleague was trying to retrieve the “AccountName” for a People Picker field – with a Powershell script – in order to update another column/list.

Here’s the full code segment :

$web = Get-SPWeb -identity "http://server/site"
$lib = $web.Lists["PeoplePhotos"]
foreach ($photo in $lib.Items) {
    $user = $photo["CompanyPerson"]
    $userObj = New-Object Microsoft.SharePoint.SPFieldUserValue($web, $user)
    $accountName = $userObj.User.UserLogin
    $accountName.substring($accountName.IndexOf("")+1)
}

Line-By-Line Explanation 

The tricky part is to make sure to use the SPFieldUserValue object – ie. ‘cast’ to the this object type – and can then get the SPUser object – and any of it’s properties.

(1) Get the web site object

(2) Get the SharePoint list

  • $lib = $web.Lists["PeoplePhotos"]

(3) Go through each item in the list – and get the field/value

  • foreach ($photo in $lib.Items) {

(4) Get the field/value – column called “CompanyPerson”

              • $user = $photo["CompanyPerson"]

(5) Convert to be a user object – ie. SPFieldUserValue

              • $userObj = New-Object Microsoft.SharePoint.SPFieldUserValue($web, $user)

(6) Get the AccountName – will be the format of “DOMAINuser”

              • $accountName = $userObj.User.UserLogin

(7) Get the “user” part – ie. drop off the DOMAIN prefix

              • $accountName.substring($accountName.IndexOf("")+1

(8) End the loop

  • }

 

Hope that helps – you have to do the same approach within C#/VB.NET – this is just “Powershell’ed”…

Smile

 

Further references :

MSDN : SPFieldUserValue Constructor (SPWeb, String)

MSDN : SPFieldUserValue.User Property

MSDN : SPUser Members

Advertisements

One thought on “SharePoint People Picker Columns (via Powershell)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s