SharePoint Online: Obtenga el inventario de la biblioteca de documentos (estructura de carpeta-subcarpeta-archivo) mediante PowerShell
Requisito: Obtener la estructura de archivos y carpetas de una biblioteca de documentos de SharePoint y exportarla a CSV.
¿Cómo obtener una lista de todos los archivos y carpetas en una biblioteca de documentos de SharePoint Online?
Si necesita obtener una lista de todos los archivos y carpetas de una biblioteca de documentos de SharePoint Online, existen diferentes formas de hacerlo. Quizás necesites limpiar tu biblioteca o simplemente tengas curiosidad por saber qué hay allí. En este artículo, le mostraremos cómo obtener una lista de todos los archivos y carpetas de una biblioteca de documentos y cómo usar PowerShell para obtener la información que necesita. ¡Empecemos!
En SharePoint Online, es fácil generar un informe de inventario de documentos para obtener una descripción general de todos los documentos de una biblioteca. Puede utilizar la función "Exportar a Excel" (no "Exportar a CSV", que exporta solo archivos y carpetas en la vista) en la biblioteca de documentos de SharePoint Online para obtener un inventario de todos los archivos y carpetas de la biblioteca. Simplemente navegue hasta su biblioteca de documentos y haga clic en el botón "Exportar a Excel" en la barra de comandos para exportar toda la lista de archivos y carpetas, junto con sus metadatos, en una biblioteca de documentos de SharePoint Online.
Esto descarga un archivo .iqy y al abrir el archivo en Excel nos proporciona el informe:
Esto puede resultar útil para solucionar problemas u obtener una descripción general rápida del contenido de una biblioteca.
SharePoint Online: PowerShell para obtener el inventario de la biblioteca de documentos
¿Está buscando una manera de obtener un inventario de todos los documentos almacenados en su biblioteca de documentos de SharePoint Online? Bueno, ¡aquí está el práctico PowerShell que puede ayudar! En esta publicación de blog, le mostraremos cómo usar PowerShell para generar un informe que enumere todos los documentos y sus propiedades, para que pueda realizar un seguimiento de qué documentos están almacenados en la biblioteca.
Exportemos todas las carpetas, subcarpetas y estructuras de archivos de una biblioteca de documentos de SharePoint Online a un archivo CSV:
#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"
#Config Parameters
$SiteURL= "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Documents"
$CSVPath = "C:\Temp\DocumentLibraryRpt.csv"
$BatchSize = 500
#Get Credentials to connect
$Cred = Get-Credential
Try {
#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 Document Library
$List =$Ctx.Web.Lists.GetByTitle($ListName)
#Define CAML Query to Get List Items in batches
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml ="
<View Scope='RecursiveAll'>
<Query>
<OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
</Query>
<RowLimit Paged='TRUE'>$BatchSize</RowLimit>
</View>"
$DataCollection = @()
Do
{
#get List items
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()
#Iterate through each item in the document library
ForEach($ListItem in $ListItems)
{
#Collect data
$Data = New-Object PSObject -Property ([Ordered] @{
Name = $ListItem.FieldValues.FileLeafRef
RelativeURL = $ListItem.FieldValues.FileRef
Type = $ListItem.FileSystemObjectType
CreatedBy = $ListItem.FieldValues.Author.Email
CreatedOn = $ListItem.FieldValues.Created
ModifiedBy = $ListItem.FieldValues.Editor.Email
ModifiedOn = $ListItem.FieldValues.Modified
FileSize = $ListItem.FieldValues.File_x0020_Size
})
$DataCollection += $Data
}
$Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
}While($Query.ListItemCollectionPosition -ne $null)
#Export Documents data to CSV
$DataCollection | Export-Csv -Path $CSVPath -Force -NoTypeInformation
Write-host -f Green "Document Library Inventory Exported to CSV!"
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
Obtener estructura de archivos y carpetas en una biblioteca de documentos usando PnP PowerShell
De manera similar, si desea exportar todas las estructuras de archivos y carpetas de una biblioteca de documentos a un archivo CSV, use este script PnP PowerShell:
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/RI/"
$ListName= "Non-Transaction"
$ReportOutput = "C:\Temp\ListInventory.csv"
#Connect to SharePoint Online site
Connect-PnPOnline $SiteURL -Interactive
#Array to store results
$Results = @()
#Get all Items from the document library
$List = Get-PnPList -Identity $ListName
$ListItems = Get-PnPListItem -List $ListName -PageSize 500
Write-host "Total Number of Items in the List:"$List.ItemCount
$ItemCounter = 0
#Iterate through each item
Foreach ($Item in $ListItems)
{
$Results += New-Object PSObject -Property ([ordered]@{
Name = $Item["FileLeafRef"]
Type = $Item.FileSystemObjectType
FileType = $Item["File_x0020_Type"]
RelativeURL = $Item["FileRef"]
CreatedBy = $Item["Author"].Email
CreatedOn = $Item["Created"]
})
$ItemCounter++
Write-Progress -PercentComplete ($ItemCounter / ($List.ItemCount) * 100) -Activity "Processing Items $ItemCounter of $($List.ItemCount)" -Status "Getting Metadata from Item '$($Item['FileLeafRef'])"
}
#Export the results to CSV
$Results | Export-Csv -Path $ReportOutput -NoTypeInformation
Write-host "Document Library Inventory Exported to CSV Successfully!"
Y el informe de salida del script:
En resumen, se puede recuperar fácilmente todos los documentos de una biblioteca de documentos de SharePoint Online utilizando el script de PowerShell, como se muestra arriba. Este script proporciona una descripción general completa del contenido almacenado en las bibliotecas de documentos de SharePoint, incluida información sobre el tipo de archivo, el propietario y la fecha de la última modificación.


