Forum Discussion

Woody's avatar
Woody
Copper Contributor
Aug 17, 2023

PnP - Add choice value in specific position

Hi!

 

With the following code I am able to add a new value to a choice column in SharePoint Online. The new value is always added at the end of the list of values.

 

The challenge is how to add a new value but in a specific position, any hint?

 

Thanks!

 

 

#Parameter
$SiteURL = "https://crescent.sharepoint.com/sites/pmo"
$ListName= "Projects"
$FieldInternalName = "Status"
  
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
$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

 

 

 

  • Hi Woody 

    "$ChoiceField.Choices" is an array and you add "Dropped" at the end of that array with the line

    $ChoiceField.Choices += "Dropped"


    To insert a value at another position in the array use this code

    $newValue="MyNewValue"
    $insertAtPosition=2
    
    $ChoiceField.Choices=$ChoiceField.Choices[0..($insertAtPosition-1)]+ $newValue + $ChoiceField.Choices[$insertAtPosition..($ChoiceField.Choices.Length-1)]


    Best Regards,
    Sven

  • SvenSieverding's avatar
    SvenSieverding
    Bronze Contributor

    Hi Woody 

    "$ChoiceField.Choices" is an array and you add "Dropped" at the end of that array with the line

    $ChoiceField.Choices += "Dropped"


    To insert a value at another position in the array use this code

    $newValue="MyNewValue"
    $insertAtPosition=2
    
    $ChoiceField.Choices=$ChoiceField.Choices[0..($insertAtPosition-1)]+ $newValue + $ChoiceField.Choices[$insertAtPosition..($ChoiceField.Choices.Length-1)]


    Best Regards,
    Sven

    • Woody's avatar
      Woody
      Copper Contributor

      Hi SvenSieverding,

       

      It worked like a charm! This is brilliant!

       

      Thanks so much!

       

      Best Regards,

      Xim

Resources