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
- $web = Get-SPWeb -identity "http://server/site"
(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”…
Further references :
MSDN : SPFieldUserValue Constructor (SPWeb, String)
it doesn’t work
LikeLike