SharePoint Online: cree varias bibliotecas de documentos usando PowerShell
Requisito: Crear varias bibliotecas de documentos en SharePoint Online mediante PowerShell.
¿Cómo crear varias bibliotecas de documentos en SharePoint Online?
¿Está buscando crear múltiples bibliotecas de documentos en SharePoint Online? Es posible que una única biblioteca de documentos no siempre sea suficiente. Tal vez desee crear una biblioteca para cada departamento de su empresa o bibliotecas de SharePoint separadas para almacenar archivos para diferentes proyectos en los que esté trabajando, o tal vez tenga una gran cantidad de documentos que deban organizarse. Cualquiera sea su motivo, crear varias bibliotecas de documentos es una práctica recomendada para administrar sus archivos, mantenerlos seguros y aprovechar al máximo su administración de documentos de SharePoint. En esta guía, le mostraremos cómo crear múltiples bibliotecas de documentos en SharePoint Online a través de PowerShell, un lenguaje de secuencias de comandos para automatizar tareas.
A veces, la biblioteca predeterminada "Documento" puede no ser suficiente y es posible que desee agregar bibliotecas de documentos adicionales al sitio. Suponiendo que tiene permisos de edición para el sitio (o es miembro del grupo de propietarios del sitio o miembros del sitio), crear varias bibliotecas de documentos en SharePoint Online es fácil y puede hacerlo en unos pocos y sencillos pasos:
Inicie sesión en su sitio de SharePoint Online >> Haga clic en el botón "+ Nuevo" en la barra de menú >> Seleccione "Biblioteca de documentos" en el menú desplegable.
-
Ingrese un nombre y una descripción para su biblioteca de documentos y luego haga clic en Crear.
Repita estos pasos para cada biblioteca adicional que desee crear. Una vez que haya creado su biblioteca de documentos, puede cargar archivos nuevos (casi todos los tipos de archivos) o crear nuevas carpetas para ayudar a organizar sus documentos. También puede establecer permisos para los miembros de su equipo o empleados y controlar quién tiene acceso a su biblioteca de documentos y personalizar aún más la biblioteca agregando campos, tipos de contenido, configurando herencia de permisos, historial de versiones, flujos de trabajo, etc., desde la configuración de la biblioteca.
PowerShell para crear múltiples bibliotecas de documentos en SharePoint Online
Microsoft SharePoint es una plataforma versátil que se puede utilizar para administrar y compartir datos para la colaboración de varias maneras. El sitio de grupo de SharePoint viene con una biblioteca de documentos predeterminada llamada "Documentos". ¿Crea frecuentemente bibliotecas de documentos de forma regular? Con PowerShell, puede crear varias bibliotecas de documentos en poco tiempo, lo que puede ser una excelente manera de aprovisionar bibliotecas de documentos de forma masiva a la vez.
¿Cómo crear múltiples bibliotecas de documentos en SharePoint Online? Podemos crear múltiples bibliotecas de documentos envolviendo el script en una función reutilizable y llamando a la función con una serie de bibliotecas de documentos para crear.
¿Cuántas bibliotecas puede tener un sitio de SharePoint? Técnicamente, puede tener 2000 listas y bibliotecas combinadas por colección de sitios (incluido el sitio raíz y los subsitios). Dado que el límite de 5000 del umbral de vista de lista afecta el rendimiento y la usabilidad de SharePoint Online, es una buena idea crear varias bibliotecas de documentos.
#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 to Create a SharePoint Online document library
Function CreateSPO-DocumentLibrary()
{
[cmdletbinding()]
param
(
[Parameter(Mandatory=$True,ValueFromPipeline)] [String[]] $LibraryNames,
[Parameter(Mandatory=$False)] [String] $Description
)
Try {
#Create Each Document Library
ForEach($LibraryName in $LibraryNames)
{
Write-host -f Yellow "`nEnsuring Document Library '$LibraryName'"
#Get All Existing Lists from the web
$Lists = $Web.Lists
$Ctx.Load($Lists)
$Ctx.ExecuteQuery()
#Check if Library name doesn't exist already
If(!($Lists.Title -contains $LibraryName))
{
#Create a new Document Library
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $LibraryName
$ListInfo.Description = $Description
$ListInfo.TemplateType = [Microsoft.SharePoint.Client.ListTemplateType]::DocumentLibrary
$Web.Lists.Add($ListInfo) | Out-Null
$Ctx.ExecuteQuery()
write-host -f Green "`tNew Document Library '$LibraryName' has been created!"
}
Else
{
Write-Host -f Magenta "`tA Document Library '$LibraryName' Already exists!"
}
}
}
Catch {
write-host -f Red "`tError:" $_.Exception.Message
}
}
#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/sites/marketing"
#Get Credentials to connect
$Cred = Get-Credential
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the web from URL
$Web = $Ctx.web
$Ctx.Load($Web)
$Ctx.executeQuery()
#Call the function to create document libraries
CreateSPO-DocumentLibrary -LibraryNames @("Document Library 1", "Document Library 2", "Document Library 3", "Document Library 4")
Cree varias bibliotecas de documentos en SharePoint Online usando PowerShell
¿Qué sucede si desea agregar algunos parámetros adicionales al script de la biblioteca de documentos masivos, como “Inicio rápido”? Aquí está mi archivo CSV con detalles de la biblioteca de documentos.
Puede descargar la plantilla CSV aquí:
Creemos bibliotecas de documentos independientes a partir de un archivo CSV 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 to Create a SharePoint Online document library
Function CreateSPO-DocumentLibrary()
{
[cmdletbinding()]
param
(
[Parameter(Mandatory=$True,ValueFromPipeline)] [String] $LibraryName,
[Parameter(Mandatory=$False)] [String] $Description,
[Parameter(Mandatory=$False)] [Switch] $ShowOnQuickLaunch
)
Try {
Write-host -f Yellow "`nEnsuring Document Library '$LibraryName'"
#Get All Existing Lists from the web
$Lists = $Web.Lists
$Ctx.Load($Lists)
$Ctx.ExecuteQuery()
#Check if Library name doesn't exist already
If(!($Lists.Title -contains $LibraryName))
{
#Set Quick Launch Option
If($ShowOnQuickLaunch.IsPresent)
{
$QuickLaunchOption = [Microsoft.SharePoint.Client.QuickLaunchOptions]::On
}
Else
{
$QuickLaunchOption = [Microsoft.SharePoint.Client.QuickLaunchOptions]::Off
}
#Create Document Library
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $LibraryName
$ListInfo.Description = $Description
$ListInfo.TemplateType = [Microsoft.SharePoint.Client.ListTemplateType]::DocumentLibrary
$List = $Web.Lists.Add($ListInfo)
$List.OnQuickLaunch = $QuickLaunchOption
$List.Update()
$Ctx.ExecuteQuery()
write-host -f Green "`tNew Document Library '$LibraryName' has been created!"
}
Else
{
Write-Host -f Magenta "`tA Document Library '$LibraryName' Already exists!"
}
}
Catch {
write-host -f Red "`tError:" $_.Exception.Message
}
}
#Set Parameters
$CSVFilePath = "C:\Temp\DocLibs.csv"
#Get Credentials to connect
$Cred = Get-Credential
#Get the CSV file
$CSVFile = Import-Csv $CSVFilePath
#Read CSV file and create a document library
ForEach($Line in $CSVFile)
{
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($Line.SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the web from URL
$Web = $Ctx.web
$Ctx.Load($Web)
$Ctx.executeQuery()
#Get the ShowOnQuickLaunch option
$ShowOnQuickLaunch = [System.Convert]::ToBoolean($Line.ShowOnQuickLaunch)
#Call the function to create document library
If($ShowOnQuickLaunch -eq $True)
{
CreateSPO-DocumentLibrary -LibraryName $Line.LibraryName -Description $Line.Description -ShowOnQuickLaunch
}
Else
{
CreateSPO-DocumentLibrary -LibraryName $Line.LibraryName -Description $Line.Description
}
}
El parámetro “TemplateType” define el tipo de biblioteca. Utilice “[Microsoft.SharePoint.Client.ListTemplateType].GetEnumNames()” para obtener todas las listas y bibliotecas disponibles que puede crear en SharePoint Online. Por ejemplo, biblioteca de imágenes, anuncios, etc.
Creación masiva de bibliotecas de documentos con PnP PowerShell
Esta vez, debo crear varias bibliotecas de documentos a partir de un archivo CSV y establecer propiedades específicas de la biblioteca de documentos, como Establecer control de versiones (versiones principales-versiones menores), experiencia de lista y permisos. El archivo CSV tiene dos columnas: LoginID y DisplayName.
Utilice este PowerShell para crear bibliotecas de documentos de forma masiva a partir de una entrada de archivo CSV.
#Set Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Shared"
$CSVFilePath = "C:\Users\salaudeen\Documents\Users.csv"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get the CSV file
$CSVFile = Import-Csv $CSVFilePath
#Read CSV file and create new library
ForEach($Line in $CSVFile)
{
Try {
#Create document library
Write-host -f Yellow "Creating Document Library:"$Line.DisplayName
New-PnPList -Title $Line.DisplayName -Template DocumentLibrary -Url $Line.LoginID -ErrorAction Stop
#Set Library Properties
Set-PnPList -Identity $Line.DisplayName -EnableVersioning $True -EnableMinorVersions $True -CopyRoleAssignments:$False -BreakRoleInheritance -ListExperience NewExperience
$Library = Get-PnPList -Identity $Line.DisplayName
#Exclude from Search Results
$Library.NoCrawl = $True
$Library.Update()
#Grant permission on List to User
$UserID = $Line.LoginID+"@crescent.com"
Set-PnPListPermission -Identity $Line.DisplayName -AddRole "Full Control" -User $UserID
Write-host -f Green "`tCreated Document Library:"$Line.DisplayName
}
Catch {
write-host -f Red "`tError:" $_.Exception.Message
}
}
También puedes usar estos scripts en sitios de OneDrive.
Las carpetas todavía se utilizan ampliamente en lugar de metadatos. Para crear varias carpetas en las bibliotecas de documentos de SharePoint, utilice: ¿Cómo agregar carpetas de forma masiva a SharePoint Online?
Conclusión
En conclusión, crear múltiples bibliotecas de documentos en SharePoint Online es un proceso sencillo y directo que se puede realizar a través de PowerShell. Al utilizar este método, puede administrar y organizar eficazmente su contenido e información de SharePoint, garantizando los requisitos comerciales, como que cada departamento o equipo tenga una biblioteca separada para almacenar archivos y documentos. Con el poder de SharePoint Online y PowerShell a su alcance, puede simplificar sus tareas de administración de contenido y asegurarse de que su sitio esté organizado y sea accesible según sea necesario.
Preguntas frecuentes:
¿Cómo obtener una biblioteca de documentos en SharePoint Online usando PowerShell?
Utilice: Get-PnPList -Identity “DocumentLibraryName” para obtener cualquier biblioteca de documentos del sitio de SharePoint Online. También puede utilizar el script CSOM PowerShell, $Ctx.Web.Lists.GetByTitle(“DocumentLibraryName”) para obtener una biblioteca.
Más información: Obtenga una biblioteca de documentos en SharePoint Online usando PowerShell
¿Cómo obtengo una lista de archivos en la biblioteca de documentos de SharePoint Online usando PowerShell?
Puede usar los scripts CSOM o PnP PowerShell para obtener una lista de todos los archivos en una biblioteca de documentos de SharePoint Online y exportar el inventario a un archivo CSV.
Más información: Cómo obtener una lista de archivos en un documento de SharePoint Online ¿Biblioteca?
¿Cómo cambiar la URL de la biblioteca de documentos en línea de SharePoint?
Para cambiar la URL de una biblioteca de documentos, puede usar la vista Exploración de archivos, SharePoint Designer o los métodos de PowerShell.
Más información: Cambiar el nombre de una URL de biblioteca de documentos en SharePoint Online



