SharePoint Online: agregue tipo de contenido a una lista o biblioteca de documentos usando PowerShell
Requisito: SharePoint Online PowerShell para agregar un tipo de contenido a la biblioteca.
¿Cómo agregar un tipo de contenido a una lista o biblioteca en SharePoint Online?
En SharePoint Online, puede agregar tipos de contenido a una lista para ayudar a definir el tipo de información que se almacena en la lista. Por ejemplo, puede agregar un tipo de contenido para "Producto" a una lista que almacena información del producto. Esto le permitiría crear nuevos elementos en la lista que se asocian automáticamente con el tipo de contenido "Producto". Este artículo le mostrará cómo agregar un tipo de contenido a una lista en SharePoint Online.
Suponiendo que ya tiene el tipo de contenido creado, estos son los pasos para agregar un tipo de contenido a la lista en SharePoint Online:
Paso 1: habilite la administración de tipos de contenido para la lista, si aún no está habilitada
Antes de agregar un tipo de contenido a una lista o biblioteca, debe habilitar la lista o biblioteca para que admita tipos de contenido.
- Navegue a la configuración de la lista >> Haga clic en el enlace "Configuración avanzada" en Configuración general.
- Configure "Sí" para "¿Permitir la administración de tipos de contenido?" opción y presione el botón Aceptar en la parte inferior de la página para guardar los cambios.
Paso 2: agregar tipo de contenido a la lista o biblioteca
Una vez que los tipos de contenido están habilitados, así es como puede agregar un tipo de contenido a una lista o biblioteca en SharePoint Online:
- Vaya a la página de configuración de la lista nuevamente. Encontrará el grupo "Tipos de contenido" creado con el tipo de contenido predeterminado en la lista (por ejemplo, encontrará el tipo de contenido "Elemento" en la lista para listas personalizadas).
-
Haga clic en el enlace "Agregar desde tipos de contenido de sitios existentes".
Desde la página Agregar tipos de contenido, seleccione el tipo de contenido que desea agregar y haga clic en el botón "Agregar" y luego en "Aceptar" una vez.
- Eso es todo. Ahora encontrará el tipo de contenido que agregó en el grupo de configuraciones de lista "Tipos de contenido".
Está bien. Ahora, veamos cómo agregar un tipo de contenido a una lista en SharePoint Online usando PowerShell.
SharePoint Online PowerShell para agregar tipos de contenido a la biblioteca
Agreguemos un tipo de contenido a la lista en SharePoint Online usando PowerShell:
#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-ContentTypeToList()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $CTypeName
)
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()
#Enable managemnt of content type in list - if its not enabled already
If($List.ContentTypesEnabled -ne $True)
{
$List.ContentTypesEnabled = $True
$List.Update()
$Ctx.ExecuteQuery()
Write-host "Content Types Enabled in the List!" -f Yellow
}
#Get all existing content types of the list
$ListContentTypes = $List.ContentTypes
$Ctx.Load($ListContentTypes)
#Get the content type to Add to list
$ContentTypeColl = $Ctx.Web.ContentTypes
$Ctx.Load($ContentTypeColl)
$Ctx.ExecuteQuery()
#Check if the content type exists in the site
$CTypeToAdd = $ContentTypeColl | Where {$_.Name -eq $CTypeName}
If($CTypeToAdd -eq $Null)
{
Write-host "Content Type '$CTypeName' doesn't exists in '$SiteURL'" -f Yellow
Return
}
#Check if content type added to the list already
$ListContentType = $ListContentTypes | Where {$_.Name -eq $CTypeName}
If($ListContentType -ne $Null)
{
Write-host "Content type '$CTypeName' already exists in the List!" -ForegroundColor Yellow
}
else
{
#Add content Type to the list or library
$AddedCtype = $List.ContentTypes.AddExistingContentType($CTypeToAdd)
$Ctx.ExecuteQuery()
Write-host "Content Type '$CTypeName' Added to '$ListName' Successfully!" -ForegroundColor Green
}
}
Catch {
write-host -f Red "Error Adding Content Type to the List!" $_.Exception.Message
}
}
#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Project Frosty"
$CTypeName="Project Template"
#Call the function
Add-ContentTypeToList -SiteURL $SiteURL -ListName $ListName -CTypeName $CTypeName
SharePoint Online PnP PowerShell para agregar tipos de contenido a la biblioteca
A continuación se explica cómo agregar un tipo de contenido a la biblioteca de documentos en SharePoint Online usando Add-PnPContentTypeToList PnP PowerShell:
#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"
$ContentTypeName="Crescent Invoice Template V2"
$ListName="Invoices"
#Get Credentials to connect
$Cred = Get-Credential
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred
#Get the content type
$ContentType = Get-PnPContentType -Identity $ContentTypeName
If($ContentType)
{
#Add Content Type to Library
Add-PnPContentTypeToList -List $ListName -ContentType $ContentType
}
else
{
Write-host -f Yellow "Could Not Find Content Type:"$ContentTypeName
}
Utilice el modificador -DefaultContentType para hacer que el tipo de contenido sea el tipo de contenido predeterminado. ¿Qué tal si agregamos algo de manejo de errores al código, como por ejemplo: verificar si la lista dada existe, verificar si el tipo de contenido no está agregado a la lista ya, etc.?
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Purchase"
$ListName = "Site Pages"
$ContentTypeName = "Site Page"
Try {
#Connect to SharePoint Online site
Connect-PnPOnline -Url $SiteURL -UseWebLogin
#Get the context
$Ctx = Get-PnPContext
#Check if the List or Library Exists
$List = Get-PnPList -Identity $ListName
If($List -ne $Null)
{
#Add Content type to the list
$ContentType = Get-PnPContentType -Identity $ContentTypeName
If($ContentType)
{
#Check if the List has the content type already
$ListContentType = Get-PnPContentType -List $ListName -Identity $ContentTypeName -ErrorAction SilentlyContinue
If(!$ListContentType)
{
#Add Content Type to List
Add-PnPContentTypeToList -List $ListName -ContentType $ContentType
Write-host -f Green "'$ContentTypeName' content type added to the List '$ListName'"
}
Else
{
Write-host -f yellow "'$ContentTypeName' content type already exists in the List!"
}
}
Else
{
Write-host -f Yellow "Could Not Find the '$ContentTypeName' Content Type!"
}
}
Else
{
Write-Host -f Yellow "List '$ListName' does not exist!"
}
}
Catch {
Write-host -f Red "Error:" $_.Exception.Message
}

