SharePoint Online: Add Choice Field to List using PowerShell

Requirement: PowerShell to add choice field to list in SharePoint Online.

How to Add Choice Field to SharePoint Online List?
Choice column in SharePoint Online is used to provide a pre-defined set of choices for metadata column. Based on the settings you configure, This field may accept single value or multiple values. Presented as a drop-down list or radio buttons when configured for single selection and displayed as check boxes when we configure it for multiple selections. To add choice field from Web UI, follow these steps:
  • Browse to your SharePoint Online site and Navigate to the target list in which you want to add Choice column.
  • Under the List tab, click on "Create Column" button in the ribbon.
  • Provide the Name to your new column, specify the type as "Choice (menu to choose from)" 
    sharepoint online add choice column to list using powershell
  • Scroll down and enter choices to the given list as one choice per line
    powershell to create choice column in sharepoint list
  • Fill other optional values such as Choice field type (Dropdown/Radio button/Checkbox) and Click on "OK" to create Choice field in SharePoint Online list.

PowerShell to Create Choice Field in SharePoint Online List:
Here is the PowerShell CSOM script to add choice column to SharePoint Online list.
#Load SharePoint CSOM 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"

#Custom function to add column to list
Function Add-ChoiceColumnToList()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ListName,
        [Parameter(Mandatory=$true)] [string] $Name,
        [Parameter(Mandatory=$true)] [string] $DisplayName,
        [Parameter(Mandatory=$true)] [string] $ChoiceValues,
        [Parameter(Mandatory=$true)] [string] $DefaultValue,
        [Parameter(Mandatory=$false)] [string] $Description="",
        [Parameter(Mandatory=$false)] [string] $IsRequired = "FALSE",
        [Parameter(Mandatory=$false)] [string] $EnforceUniqueValues= "FALSE",
        [Parameter(Mandatory=$false)] [string] $Format ="Dropdown",
        [Parameter(Mandatory=$false)] [string] $FillInChoice="FALSE"
    )

    #Generate new GUID for Field ID
    $FieldID = New-Guid

    Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup 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()

        #Check if the column exists in list already
        $Fields = $List.Fields
        $Ctx.Load($Fields)
        $Ctx.executeQuery()
        $NewField = $Fields | where { ($_.Internalname -eq $Name) -or ($_.Title -eq $DisplayName) }
        if($NewField -ne $NULL)  
        {
            Write-host "Column $Name already exists in the List!" -f Yellow
        }
        else
        {
           #Frame Choices
            $ChoiceOptions=""
            $Choices = $ChoiceValues.Split(",")
            foreach ($Choice in $Choices)
            {
                $ChoiceOptions = $ChoiceOptions + "<CHOICE>$Choice</CHOICE>"
            }
            #Define XML for Field Schema
            $FieldSchema = "<Field Type='Choice' ID='{$FieldID}' DisplayName='$DisplayName' Name='$Name' Description='$Description' Required='$IsRequired' FillInChoice='$FillInChoice' Format='$Format'><Default>$DefaultValue</Default> <CHOICES>$ChoiceOptions</CHOICES></Field>"
            $NewField = $List.Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint)
            $Ctx.ExecuteQuery()    

            Write-host "New Column Added to the List Successfully!" -ForegroundColor Green  
        }
    }
    Catch {
        write-host -f Red "Error Adding Column to List!" $_.Exception.Message
    }
} 

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$Name="ProjectDepartment"
$DisplayName="Project Department"
$Description="Enter the Project Department"
$ChoiceValues="IT,Sales,Operations,Marketing,HR"
$DefaultValue="IT"
$Format="RadioButtons" #Override default parameter value Dropdown

#Call the function to add column to list
Add-ChoiceColumnToList -SiteURL $SiteURL -ListName $ListName -Name $Name -DisplayName $DisplayName -Description $Description -Format $Format -ChoiceValues $ChoiceValues -DefaultValue $DefaultValue
This PowerShell script adds a new choice column for given parameters.

Tips: How to Add MultiChoice Column? Just change "Field Type='MultiChoice'" in the Field schema XML

Add Choice Field to SharePoint Online List using PnP PowerShell
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$ListName= "Projects"

#Get Credentials to connect
$Cred = Get-Credential

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred

#Add Choice Field
Add-PnPField -List $ListName -DisplayName "Department" -InternalName "Department" -Type Choice -AddToDefaultView -Choices "Sales","Marketing","Purchase", "IT", "HR" 
Similarly, you can add a choice column to SharePoint Online list from XML too
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$ListName= "Projects"

#Get Credentials to connect
$Cred = Get-Credential

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred

#Genrate New GUID for List ID
$FieldID = ([GUID]::NewGuid()).GUID

#Define XML Schema for Choice Field
$FieldXML= "<Field Type='Choice' Name='Priority' ID='$FieldID' DisplayName='Priority'>
                 <CHOICES>
                      <CHOICE>(1) High</CHOICE>
                      <CHOICE>(2) Normal</CHOICE>
                      <CHOICE>(3) Low</CHOICE>
                </CHOICES>
                <Default>(2) Normal</Default>
            </Field>"

#Add Choice Field to list from XML
Add-PnPFieldFromXml -FieldXml $FieldXML -List $ListName
Change the Field type to "MultiChoice" if you need a multiple choices column. Set Format='RadioButtons' for radio buttons choice.
SharePoint Online: Add Choice Field to List using PowerShell SharePoint Online: Add Choice Field to List using PowerShell Reviewed by Salaudeen Rajack on September 26, 2016 Rating: 5

2 comments:

Please Login and comment to get your questions answered!

Powered by Blogger.