Búsqueda de sitios web

SharePoint Online: agregar columna al tipo de contenido de la lista usando PowerShell


Requisito: Agregue un campo para enumerar el tipo de contenido en SharePoint Online.

¿Cómo agregar una columna a un tipo de contenido de lista o biblioteca en SharePoint Online?

PowerShell es un potente lenguaje de secuencias de comandos que puede ayudar a automatizar muchas tareas en SharePoint. Puede haber ocasiones en las que necesite agregar una columna a un tipo de contenido de lista. Puede hacerlo manualmente, pero puede llevar mucho tiempo si tiene muchas listas y tipos de contenido. Esta publicación de blog le mostrará cómo agregar una columna a un tipo de contenido de lista de SharePoint Online usando PowerShell.

Si desea agregar un campo a una lista o tipo de contenido de biblioteca, siga estos pasos:

  1. Vaya a la lista o configuración de la biblioteca >> Haga clic en el nombre del tipo de contenido apropiado en la página de configuración de la lista.
  2. En la página Tipo de contenido de la lista, en la sección de columnas, haga clic en el enlace "Agregar desde un sitio existente o columnas de lista".
  3. Seleccione el grupo de columnas apropiado y luego seleccione la columna que desea agregar al tipo de contenido, haga clic en el botón "Agregar" y luego en Aceptar para agregar esa columna a su tipo de contenido.

Puede agregar columnas desde las columnas de la lista existente o desde las columnas del sitio.

SharePoint Online: PowerShell para agregar un campo al tipo de contenido de la lista

Agreguemos un campo para enumerar el tipo de contenido usando PowerShell. A continuación se explica cómo utilizar PowerShell para agregar una columna a un tipo de contenido de lista:


#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"

Function Add-ColumnToListContentType()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ListName,
        [Parameter(Mandatory=$true)] [string] $ContentTypeName,
        [Parameter(Mandatory=$true)] [string] $ColumnName,
        [Parameter(Mandatory=$false)] [bool] $IsSiteColumn=$True
    )

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

        #Get the content type from list
        $ContentTypeColl = $List.ContentTypes
        $Ctx.Load($ContentTypeColl)
        $Ctx.ExecuteQuery()
        
        #Check if the content type exists in the list        
        $ContentType = $ContentTypeColl | Where {$_.Name -eq $ContentTypeName}
        If($ContentType -eq $Null)
        { 
            Write-host "Content Type '$ContentTypeName' doesn't exists in '$ListName'" -f Yellow
            Return 
        }

        #Get the column to add: Either site column or existing list's column
        If($IsSiteColumn)
        {
            $ColumnColl = $Ctx.Web.Fields
        }
        else #List Column
        {
            $ColumnColl = $List.Fields
        }
        $Ctx.Load($ColumnColl)
        $Ctx.ExecuteQuery()
        $Column = $ColumnColl | Where {$_.Title -eq $ColumnName}
    
        #Check if given column exists
        if($Column -eq $Null)
        {
            Write-host "Column '$ColumnName' doesn't exists!" -f Yellow
            Return
        }
        else
        {
            #Check if column already added to the content type
            $FieldCollection = $ContentType.Fields
            $Ctx.Load($FieldCollection)
            $Ctx.ExecuteQuery()
            $Field = $FieldCollection | Where {$_.Title -eq $ColumnName}
            if($Field -ne $Null)
            {
                Write-host "Column '$ColumnName' Already Exists in the content type!" -f Yellow
                Return
            }
    
            #Add field to content type
            $FieldLink = New-Object Microsoft.SharePoint.Client.FieldLinkCreationInformation
            $FieldLink.Field = $Column
            [Void]$ContentType.FieldLinks.Add($FieldLink)
            $ContentType.Update($false)
            $Ctx.ExecuteQuery() 
       
            Write-host "Column '$ColumnName' Added to '$ContentTypeName' Successfully!" -ForegroundColor Green
        }
   }
    Catch {
        write-host -f Red "Error Adding Column to Content Type!" $_.Exception.Message
    } 
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$ContentTypeName="Projects"
$ColumnName="Head Count"
$IsSiteColumn=$false

#Call the function
Add-ColumnToListContentType -SiteURL $SiteURL -ListName $ListName -ContentTypeName $ContentTypeName -ColumnName $ColumnName 

Según el valor del parámetro "IsSiteColumn", este script puede agregar una columna de sitio o una columna de lista a un tipo de contenido determinado.

PnP PowerShell para agregar una columna para enumerar el tipo de contenido en SharePoint Online


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/PMO"
$ListName = "Projects"
$ContentTypeName = "Crescent Project V2"
$FieldName = "Department" 

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive
    
    #Get the Content Type from the List
    $ContentType = Get-PnPContentType -Identity $ContentTypeName -List $ListName

    #Add a column list
    $Field =  Add-PnPField -List $ListName -DisplayName $FieldName -InternalName $FieldName -Type Choice -Choices "Sales","Marketing","Purchase" -AddToDefaultView

    #Add the column to Content type
    Add-PnPFieldToContentType -Field $Field -ContentType $ContentType
}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Si necesita agregar un campo al tipo de contenido del sitio, use: SharePoint Online: ¿Cómo agregar una columna de sitio al tipo de contenido usando PowerShell?

Artículos relacionados