Búsqueda de sitios web

SharePoint Online: agregar campo de elección a la lista usando PowerShell


Requisito: PowerShell para agregar un campo de elección a la lista en SharePoint Online.

¿Cómo agregar un campo de elección a la lista de SharePoint Online?

La columna de opciones en SharePoint Online se usa para proporcionar un conjunto predefinido de opciones para la columna de metadatos. Según los ajustes que configure, este campo puede aceptar un valor único o varios valores. Cuando se configura para selección única, es una lista desplegable o botones de opción y se muestra como casillas de verificación cuando lo configuramos para selecciones múltiples. Para agregar un campo de elección desde la interfaz de usuario web, siga estos pasos:

  1. Vaya a su sitio de SharePoint Online y navegue hasta la lista de destino en la que desea agregar la columna Elección.
  2. En la pestaña Lista, haga clic en el botón "Crear columna" en la cinta.
  3. Proporcione el Nombre a su nueva columna, especifique el tipo como "Elección (menú para elegir)"

  4. Desplácese hacia abajo e ingrese opciones en la lista dada como una opción por línea

  5. Complete otros valores opcionales, como el tipo de campo de elección (desplegable/botón de opción/casilla de verificación) y haga clic en "Aceptar" para crear un campo de elección en la lista de SharePoint Online.

PowerShell para crear un campo de elección en la lista de SharePoint Online:

Aquí está el script CSOM de PowerShell para agregar una columna de opciones a la lista de SharePoint Online.


#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=[string]::Empty,
        [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=[string]::Empty
            $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

Este script de PowerShell agrega una nueva columna de opciones para parámetros determinados.

Consejos: ¿Cómo agregar una columna de opciones múltiples? Simplemente cambie "Tipo de campo='MultiChoice'" en el esquema de campo XML

Agregar campo de elección a la lista de SharePoint Online usando PnP PowerShell

La columna Elección permite a los usuarios seleccionar de una lista predefinida de valores al ingresar datos en la lista. Veamos cómo agregar un campo de elección a una lista de SharePoint Online usando PnP PowerShell:


#Config Variables
$SiteURL = "https://Crescent.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" 

De manera similar, también puede agregar una columna de elección a la lista de SharePoint Online desde XML.


#Config Variables
$SiteURL = "https://Crescent.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

Cambie el tipo de campo a "MultiChoice" si necesita una columna de opción múltiple. Establezca Formato='RadioButtons' para elegir los botones de opción.

Artículos relacionados