SharePoint Online: Update Choices in Choice Field using PowerShell

Requirement: Update choice field choices in SharePoint Online using PowerShell
sharepoint online update choice field using powershell

SharePoint Online: PowerShell to Update Choice Field
#Load SharePoint Online Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

##Variables for Processing
$SiteUrl = "https://crescenttech.sharepoint.com"
$ListName= "Projects"
$FieldName="Category"
#Define Choices
$Choices = @("Growth Capital","Private Investment","Development", "Start up", "Real Estate")
  
#Get Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
  
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Ctx.Credentials = $Credentials

#Get the List
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
$Ctx.ExecuteQuery()

#Get the field
$Field = $List.Fields.GetByInternalNameOrTitle($FieldName)
$Ctx.Load($Field)
$Ctx.ExecuteQuery()

#Cast the field to Choice Field
$ChoiceField = New-Object Microsoft.SharePoint.Client.FieldMultiChoice($Ctx, $Field.Path)
$Ctx.Load($ChoiceField)
$Ctx.ExecuteQuery()

#$choiceField.Choices.Clear()
$ChoiceField.Choices = $Choices            
$ChoiceField.UpdateAndPushChanges($True)
$Ctx.ExecuteQuery()

Write-host "Choice Field has been Updated!" -ForegroundColor Green

If you want to append to existing choices, use:
$ChoiceField.Choices += $Choices  
This adds value to choice field's existing choices.

PnP PowerShell to Add Choice to a Choice Column in SharePoint Online
#Parameter
$SiteURL = "https://crescent.sharepoint.com/sites/pmo"
$ListName= "Projects"
$FieldInternalName = "Status"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin
$Ctx = Get-PnPContext

#Get the Field to update
$Field = Get-PnPField –Identity $FieldInternalName -List $ListName

#Cast the field to Choice Field
$ChoiceField = New-Object Microsoft.SharePoint.Client.FieldChoice($Ctx, $Field.Path)
$Ctx.Load($ChoiceField)
Invoke-PnPQuery

#Add a Choice Value
$ChoiceField.Choices += "Dropped"
$ChoiceField.UpdateAndPushChanges($True)
Invoke-PnPQuery

Here is my another post on get and set choice field values using PowerShell: How to Read/Write Choice Field Values using PowerShell?

1 comment:

  1. How can i delete Values in the Choices?

    Thanks

    ReplyDelete

Please Login and comment to get your questions answered!

Powered by Blogger.