Add Yes/No (Check Box) Field to SharePoint List using PowerShell
Requirement: Add Yes/No (Check box) field to SharePoint List.
How to Create a Yes/No Check box column in SharePoint List?
Follow these steps to add a Yes/No field to a SharePoint List:
- Browse your SharePoint site and navigate to the target list where you want to add the Yes/No column.
- Under the List tab, click the “Create Column” button in the ribbon.
- Provide the Name to your new column, and specify the type as “Yes/No Check box”.Â
- Fill in other optional values such as field description, Default Value, and Click on “OK” to create a Yes/No check box field in the SharePoint list.
SharePoint PowerShell to Create Yes/No Field in List or Library:
Use this PowerShell script to add the Yes/No column to the SharePoint list.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Function to add Field to list
Function Add-YesNoFieldToList()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $FieldName,
[Parameter(Mandatory=$true)] [string] $DisplayName,
[Parameter(Mandatory=$false)] [string] $Description,
[Parameter(Mandatory=$false)] [string] $DefaultValue = "0"
)
#Generate new GUID for Field ID
$FieldID = [guid]::newguid()
Try {
#Get Web List and Objects
$Web = Get-SPWeb $SiteURL
$List = $Web.Lists[$ListName]
#Check if the Field exists in list already
$Fields = $List.Fields
$NewField = $Fields | where { ($_.Internalname -eq $Name) -or ($_.Title -eq $DisplayName) }
if($NewField -ne $NULL)
{
Write-host "Field '$FieldName' already exists in the List!" -f Yellow
}
else
{
#Define XML for Field Schema
$FieldSchema = "<Field Type='Boolean' ID='{$FieldID}' DisplayName='$DisplayName' Name='$FieldName' Description='$Description'><Default>$DefaultValue</Default></Field>"
$NewField = $List.Fields.AddFieldAsXml($FieldSchema,$True,[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)
Write-host "New Field Added to the List Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Adding Field to List!" $_.Exception.Message
}
}
#Set parameter values
$SiteURL="https://intranet.crescent.com/sites/projects"
$ListName="Projects"
$FieldName="IsActive"
$DisplayName="Is Active"
$Description="Specify if the Project is Active"
$DefaultValue="1" #0 for No / 1 for Yes
#Call the function to add field to list
Add-YesNoFieldToList -SiteURL $SiteURL -ListName $ListName -FieldName $FieldName -DisplayName $DisplayName -Description $Description -DefaultValue $DefaultValue
The field schema supports more attributes such as Group, Indexed, ShowInNewForm, etc. Refer to this MSDN link for the complete field schema: https://docs.microsoft.com/en-us/sharepoint/dev/schema/field-element-field