Update Choice Field values using CSOM in PowerShell

I wanted a CSOM script in PowerShell to add a new value to a choice field in SharePoint. Most of the examples I found were in CSOM Managed Code (C#) but could not find anything in PowerShell.

I came up with the embedded code.

The client assemblies are referenced

  •  SharePoint Assemblies\Microsoft.SharePoint.Client.dll
  • SharePoint Assemblies\Microsoft.SharePoint.Client.Runtime.dll

I have created the function Add-ChoiceValueToField to contain the logic to add a value to a choice field.

The Field object has to be cast into FieldChoice to expose the Choices property. In PowerShell the CastTo method can be accessed using the MakeGenericMethod.

[Microsoft.SharePoint.Client.ClientContext].GetMethod("CastTo").MakeGenericMethod([Microsoft.SharePoint.Client.FieldChoice]).Invoke($ctx,$field)

I have used the  Load-CSOMProperties function from script Load-CSOMProperties.ps1  to load the existing property “Choices” which an immutable collection.  Load-CSOMProperties.ps1  is available from blog post Loading Specific Values Using Lambda Expressions and the SharePoint CSOM API with Windows PowerShell to help with querying object properties like Lambda expressions in C#.

Load-CSOMProperties -object $fieldChoice -propertyNames @("Choices") ;

I have saved the collection in an array object $FieldChoiceValues to which the existing choice values have been added. If the value to be added does not exist, then it is added to the array object  $FieldChoiceValues.

Finally the Field Choices property is updated with the array object $FieldChoiceValues

$fieldChoice.Choices = $FieldChoiceValues;
$fieldChoice.Update()

The function can be called as follows

Add-ChoiceValueToField -ctx $ctx -ListTitle "ListTestManually" -FieldName "TypeNum" -ChoiceValue "7"

 

Advertisements

3 thoughts on “Update Choice Field values using CSOM in PowerShell

  1. Awesome! AND timely!
    Two questions:
    Will this work against a Sharepoint Online doc library with more than 5000 items?
    Can this alter an existing choice value as well as adding a new one?
    Thx,
    Barry

    Like

    • Hi Barry

      It will work against a document library as well independent of number of items present. To update existing choice value, the method will have to be modified to find the old choice value and update it with new choice value.

      Thanks
      Reshmee

      Like

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