SharePoint 2010 Powershell read lookup or person field & add value

Powershell is great, powershell can do really great things if you know how to. So i would like to share some experiences with you.

Basic: Get the list and the item of your list:



$Web = Get-SPWeb "http://server/sites/sitecollection"
$List = $Web.Lists["Listname"]
//All items where ID is equal "1" you can set it as you like
$Item = $List.Items | ? {$_["ID"] -eq "1"}
$groupcol = $Item["YourField"]


Reading the values of a lookup



$ValueCollection = New-Object Microsoft.SharePoint.SPFieldUserValueCollection
foreach($group in $groupcol)
{
$group.lookupvalue
}


Adding value to this field



//This value collection will be saved afterwords into the field and it overrides the old values
$ValueCollection = New-Object Microsoft.SharePoint.SPFieldUserValueCollection
foreach($group in $groupcol)
{
//Add the old values to the new Value collection
$ValueCollection.Add($group)
$myGroup.id = "1"
$myGroup.Name = "Test"
$GroupValue = new-Object Microsoft.SharePoint.SPFieldUserValue($Web,
$myGroup.id, $myGroup.Name)
$ValueCollection.Add($GroupValue)
}
$Item["YourField"] = $ValueCollection
$Item.Update()


Hope this helps.

..:: I LIKE SHAREPOINT ::..

The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

Karsten Pohnke About Karsten Pohnke
He is Consultant for SharePoint Solutions for collaboration, communication and business processes. He provides his customers applications based on standard features as well as development or combining the power of several microsoft tools like Dynamics CRM. In his free time he tries to collect tipps and worthy experience in this blog.