In this super short post I’ll show how to use Powershell and CSOM (Client-side Object Model) to set the value of a multi-value Lookup field column in a list or library.
To set the value for a single-value column you just need to set the column value to a FieldLookupValue instance, note that only the LookupId property can be set, so you have to know/get what the list item ID of the target lookup item is.
For a multi-value column, you have to supply a FieldLookupValue[]
array ~ in C# this is easy enough, but in Powershell it’s not obvious how to do it.
The trick is to create a vanilla Object[]
array and add FieldLookupValue instance to it, then to convert that to an FieldLookupValue[]
array, and use that as the item column value.
Here’s the code;
<# | |
get $ctx and $site | |
#> | |
$web = $site.OpenWeb("news") | |
$list = $web.Lists.GetByTitle("Posts") | |
$item = $list.GetItemById(6) | |
$ctx.Load($web) | |
$ctx.Load($list) | |
$ctx.Load($item) | |
$ctx.ExecuteQuery() | |
$mvLookup = $item["MultiValueLookupColumnName"] | |
$mvLookup |% { "Lookup Value: $($_.LookupId):$($_.LookupValue)" } | |
# create an Object[] and add FieldLookupValue instances | |
$lookupValueCollection = @() | |
$lookupValue = New-Object Microsoft.SharePoint.Client.FieldLookupValue | |
$lookupValue.LookupId = 4 | |
$lookupValueCollection += $lookupValue | |
$lookupValue = New-Object Microsoft.SharePoint.Client.FieldLookupValue | |
$lookupValue.LookupId = 5 | |
$lookupValueCollection += $lookupValue | |
# convert the Object[] to a FieldLookupValue[] | |
$mvLookup = [Microsoft.SharePoint.Client.FieldLookupValue[]]$lookupValueCollection | |
# set multi-value lookup field value | |
$item["MultiValueLookupColumnName"] = $mvLookup | |
$item.Update() | |
$ctx.ExecuteQuery() | |
This is just what i’m looking for…..please can you repost the code Phil.
Howard/
The code is available in the Gist linked in the post.
Thanks Phil, It wasn’t showing. Different browser and yes I can see it now.. thanks Howard
Excellent job Phil; I now have the multi value update working. However I’m now getting errors when updating a single value lookup field. The exception is “Value does not fall within the expected range”. This is my code ;-
$lookupValue = New-Object Microsoft.SharePoint.Client.FieldLookupValue
$lookupValue.LookupId = GetLookupFieldIDs -lookupField “Title” -lookupValues “$($Vendor.Text)” -lookupSourceList “$strSharePointVendorList”
$item[“ApplicationVendor0”] = $lookupValue
GetLookupFieldIDs is a function that just returns an integer of the list item ID that I want to use.
Any ideas why this isn’t working? lookupvalue seems to be cast correctly and only the LookupId is populated.
LookupId LookupValue TypeId
——– ———– ——
428 {f1d34cc0-9b50-4a78-be…