PnP PowerShell - add choice column values

Copper Contributor

Hi Folks,

Trying to run a PS Script to update a choice column in a site, but keep getting the following error:

Exception calling "Remove" with "1" argument(s): "Collection was of a fixed size."

 

The Scipt is:

$SupplierChoices = Get-PnPField -Identity "Supplier"
$SupplierChoices.Choices.Add($namechoices)
$SupplierChoices.Update()

$namechoices would look like the following: "Choice 1","Choice 2", "Choice 3" so on...

 

2 Replies

I've used this successfully:

 

$FieldType = [Microsoft.SharePoint.SPFieldType]::Choice
$FieldName="FedSEP POC"
$IsRequired = $False
$ChoiceValues = New-Object Microsoft.SharePoint.SPFieldMultiChoiceValue;
$ChoiceValues.Add("Choice 1")
$ChoiceValues.Add("Choice 2")
Add-ChoiceFieldToList $SiteURL $ListName $FieldName $FieldType $IsRequired $ChoiceValues "" $true

 

Function Add-ChoiceFieldToList($SiteURL,$ListName, $FieldName, $FieldType, $IsRequired, $ChoiceValues, $DefaultValue, $FillInChoice)
{
#Set the Error Action
$ErrorActionPreference = "Stop"

Try{
#Get the List
$List = (Get-SPWeb $SiteURL).Lists.TryGetList($ListName)

#Check if List with specific name exists
if($List -ne $null)
{
if(!$List.Fields.ContainsField($FieldName))
{
#Add columns to the List
$newFieldName = $List.Fields.Add($FieldName,$FieldType,$IsRequired)

$newField = $List.Fields.GetFieldByInternalName($newFieldName)

#Loop through the options and

for($i=0;$i -lt $ChoiceValues.Count;$i++)
{
#$ChoiceValues[$i]
$newField.Choices.Add($ChoiceValues[$i])

#$multichoicevalues[$c]
};

$newField.DefaultValue = $DefaultValue
$newField.FillInChoice = $FillInChoice
$newField.Update()

#Update the List
$List.Update()

#Update the default view to include the new column
$View = $List.DefaultView # OR $List.Views["All Items"]
$View.ViewFields.Add($FieldName)
$View.Update()

write-host "New Column '$FieldName' Added to the List!" -ForegroundColor Green
}
else
{
write-host "Field '$FieldName' Already Exists in the List" -ForegroundColor Red
}
}
else
{
write-host "List '$ListName' doesn't exists!" -ForegroundColor Red
}
}
catch {
Write-Host $_.Exception.Message -ForegroundColor Red
}
finally {
#Reset the Error Action to Default
$ErrorActionPreference = "Continue"
}
}

Hey Steve,

 

Thanks for the response!

 

Looks like that script is creating a new column? The column I have already exists in the site, is it possible to add choices to a column that column instead of creating a new one?