SharePoint Online: Exportar el historial de versiones de la lista a Excel usando PowerShell
Requisito: Exportar todas las versiones de elementos de lista de SharePoint Online a un archivo CSV (Excel).
PowerShell para extraer y exportar el historial de versiones de elementos de la lista a un archivo CSV
Como administrador, puede haber ocasiones en las que necesite exportar el historial de versiones de una lista de SharePoint Online a Excel para su posterior análisis. Podemos exportar el historial de versiones de la lista a Excel usando PowerShell. Este artículo supone que tiene una lista de SharePoint Online existente con las columnas que se indican a continuación y es posible que deba crear y cambiar columnas según sus requisitos. Este artículo lo guiará a través de los pasos para exportar el historial de versiones de la lista de SharePoint Online a Excel 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 Export-VersionHistory()
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $ListName,
[Parameter(Mandatory=$true)] [string] $CSVFile
)
Try {
#Delete the Output report file if exists
if (Test-Path $CSVFile) { Remove-Item $CSVFile }
#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 List
$List = $Ctx.Web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
$Ctx.ExecuteQuery()
#Define Query to get List Items in batch
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml = "<View Scope='RecursiveAll'><RowLimit>2000</RowLimit></View>"
#Batch process list items - to mitigate list threshold issue on larger lists
Do {
#Get items from the list in batches
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()
$Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
#Array to hold result
$VersionHistoryData = @()
#Iterate throgh each item
Foreach ($Item in $ListItems)
{
write-host "Processing Item:" $item.id -f Yellow
#Get all versions of the list item
$Versions = $Item.versions
$ctx.Load($Versions)
$Ctx.ExecuteQuery()
If($Versions.count -gt 0)
{
#Iterate each version
Foreach($Version in $Versions)
{
#Get the Creator object of the version
$CreatedBy = $Version.createdby
$Ctx.Load($CreatedBy)
$Ctx.ExecuteQuery()
#Send Data to object array
$VersionHistoryData += New-Object PSObject -Property @{
'Item ID' = $Item.ID
'Title' = $Version.FieldValues["Title"]
'Version Label' = $Version.VersionLabel
'Version ID' = ($Version.VersionId/512)
'Created On' = (Get-Date ($Version.Created) -Format "yyyy-MM-dd/HH:mm:ss")
'Created By' = $CreatedBy.Email
}
}
}
}
}While($Query.ListItemCollectionPosition -ne $null)
#Export the data to CSV
$VersionHistoryData | Export-Csv $CSVFile -Append -NoTypeInformation
Write-host -f Green "Version History Exported Successfully to:" $CSVFile
}
Catch {
write-host -f Red "Error Exporting version History to CSV!" $_.Exception.Message
}
}
#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"
$CSVFile="C:\Temp\VersionHistory.csv"
#Call the function to generate version History Report
Export-VersionHistory -SiteURL $SiteURL -ListName $ListName -CSVFile $CSVFile
He utilizado el valor del campo "Título" en el script. Puede agregar cualquier otra columna con: $version.FieldValues[“ColumnInternalName”]
Este script genera un archivo CSV con datos de versión como:
- Etiqueta de versión,
- ID de versión
- Cuando se creó la versión.
- ¿Quién creó la versión?
- Valor del campo de título de la versión (¡también puedes agregar cualquier campo adicional!)
Para SharePoint local, use este script: ¿Cómo exportar el historial de versiones de SharePoint a CSV usando PowerShell?
PnP PowerShell para exportar el historial de versiones de todos los elementos de una lista
Exportemos todas las versiones anteriores de elementos de una lista a un archivo CSV usando PnP PowerShell.
#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/PMO"
$ListName = "Projects"
$CSVPath = "C:\Temp\ProjectsVersionsRpt.csv"
#Connect to SharePoint Online site
Connect-PnPOnline -Url $SiteURL -Interactive
#Get All Fields from List
$ListFields = Get-PnPField -List $ListName | Where {!$_.Hidden}
$VersionHistoryData = @()
#Get All List Items - Exclude Folders
Get-PnPListItem -List $ListName -PageSize 500 | Where {$_.FileSystemObjectType -ne "Folder"} | ForEach-Object {
Write-host "Getting Versioning Data of Item:"$_.ID
$Versions = Get-PnPProperty -ClientObject $_ -Property Versions
ForEach($Version in $Versions)
{
$VersionHistory = New-Object PSObject
$VersionHistory | Add-Member -MemberType NoteProperty -Name "Version ID" -Value ($Version.VersionId/512)
$VersionHistory | Add-Member -MemberType NoteProperty -Name "Version Label" -Value $Version.VersionLabel
$VersionHistory | Add-Member -MemberType NoteProperty -Name "Created On" -Value (Get-Date ($Version.Created) -Format "yyyy-MM-dd/HH:mm:ss")
#Get Value of all other Fields
$ListFields | ForEach-Object {
#Handle Special Fields
$FieldType = $_.TypeAsString
If($FieldType -eq "User" -or $FieldType -eq "UserMulti" -or $FieldType -eq "Lookup" -or $FieldType -eq "LookupMulti")
{
$FieldValue = $Version[$_.InternalName].LookupValue -join "; "
}
ElseIf($FieldType -eq "URL") #Hyperlink
{
$URL = $Version[$_.InternalName].URL
$Description = $Version[$_.InternalName].Description
$FieldValue = "$URL, $Description"
}
ElseIf($FieldType -eq "TaxonomyFieldType" -or $FieldType -eq "TaxonomyFieldTypeMulti") #MMS
{
$FieldValue = $Version[$_.InternalName].Label -join "; "
}
Else
{
#Get Source Field Value
$FieldValue = $Version[$_.InternalName]
}
#Append Version data
$VersionHistory | Add-Member -MemberType NoteProperty -Name $_.InternalName -Value $FieldValue
}
$VersionHistoryData+=$VersionHistory
}
}
$VersionHistoryData | Export-Csv $CSVPath -NoTypeInformation
No olvide reemplazar las variables SiteURL, ListName y CSVPath con los valores relevantes para su entorno.
