Power Shell script to restore versions of files in a SharePoint library in bulk

Aaron Diaz 0 Reputation points
2024-12-04T15:50:50.23+00:00

Hello everyone

Recently, my business account was hacked, and all my files were encrypted. I need a PowerShell script that allows me to restore the previous unencrypted versions of all the files in my document library. Here's the script I've been using, but I'd like to know if there's a more efficient way or if anyone can suggest improvements:

I have problems restoring the files, the script works fine to download all the files from the library, but it does not run to restore the files, I also tried to use the restore library option, but, in addition, in the particular case, it is some folders within the library that we want to restore the files

I appreciate any help or suggestions you can offer. Thank you in advance!

# Conectar a SharePoint Online
Connect-PnPOnline -Url "https://******.sharepoint.com/sites/***********/controldecalidad" -ClientId "ca8fce33-3861-4043-b2bf-55e422******" -Tenant "******.onmicrosoft.com" -Interactive
if ($?) {
    Write-Output "Conexión a SharePoint establecida correctamente."
} else {
    Write-Output "Error al conectar a SharePoint."
    exit
}

# Obtener la biblioteca de documentos
try {
    $library = Get-PnPList -Identity "Aaron"
    Write-Output "Biblioteca obtenida: $library"
} catch {
    Write-Output "Error al obtener la biblioteca: $_"
    exit
}

# Obtener todos los documentos en la biblioteca
try {
    $documents = Get-PnPListItem -List $library -PageSize 1000 -Fields FileRef, FileLeafRef
    Write-Output "Documentos obtenidos: $($documents.Count)"
} catch {
    Write-Output "Error al obtener los documentos: $_"
    exit
}

# Restaurar la versión anterior de cada documento
foreach ($doc in $documents) {
    $fileUrl = $doc["FileRef"]
    Write-Output "Procesando archivo: $fileUrl"
    try {
        $fileVersions = Get-PnPFileVersion -Url $fileUrl
        if ($fileVersions.Count -gt 1) {
            # Restaurar la versión anterior
            $previousVersion = $fileVersions[1]
            Restore-PnPFileVersion -Url $fileUrl -VersionLabel $previousVersion.VersionLabel
            Write-Output "Restaurado: $fileUrl a la versión $($previousVersion.VersionLabel)"
        } else {
            Write-Output "No hay versiones anteriores para: $fileUrl"
        }
    } catch {
        Write-Output "Error al procesar el archivo: $fileUrl. Detalles del error: $_"
    }
}
Microsoft 365
Microsoft 365
Formerly Office 365, is a line of subscription services offered by Microsoft which adds to and includes the Microsoft Office product line.
5,768 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
3,425 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,864 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Emily Du-MSFT 51,271 Reputation points Microsoft External Staff
    2024-12-05T02:27:12.3766667+00:00

    You could use following PowerShell to restore previous versions of files from a folder.

    #Function to Restore Previous Versions of all Files in a Library
    Function Restore-PreviousVersion
    {
        [CmdletBinding()]
        Param
        (
            [Parameter(Mandatory=$true,ValueFromPipeline=$true)][Microsoft.SharePoint.Client.List]$Library
        )
     
        Begin
        {
            $BatchSize = 2000
            $global:Counter = 0
        }
        Process
        {
            #Get All Files from the folder in batches
            $AllItems = Get-PnPFolderItem -FolderSiteRelativeUrl $ParentFolderURL -ItemName $FolderName
             
            #Process All Files from the Library
            $global:Counter = 1
            ForEach($Item in $AllItems)
            {
                #Get File and Versions from the List Item
                Get-PnPProperty -ClientObject $Item -Property File | Out-Null
                Get-PnPProperty -ClientObject $Item.File -Property Versions | Out-Null
     
                If($Item.File.Versions.Count -gt 0)
                {
                    #Get the previous Version's Label
                    $VersionLabel = $Item.File.Versions[$Item.File.Versions.Count-1].VersionLabel
     
                    Write-Host "$(Get-Date) - ($($Counter)/$($AllItems.Count)) - Restoring version $VersionLabel for $($Item.File.Name)"
                    $item.File.Versions.RestoreByLabel($VersionLabel)
                    Invoke-PnPQuery
                }
                else
                {
                    Write-Host "$(Get-Date) - ($($Counter)/$($AllItems.Count)) - Skipping $($Item.File.Name) as there are no previous versions!"
                }
                $Counter++
            }
        }
        end
        {
        }
    }
     
    #Set Parameters
    $SiteURL = "https://tenant.sharepoint.com/sites/test"
    $ParentFolderURL = "/Shared Documents"
    $FolderName = "foldername"
    #Connect to SharePoint Online
    Connect-PnPOnline -Url $SiteURL -Interactive
     
     
    #Call the function to Restore Previous Versions of all files
    $Library | Restore-PreviousVersion
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.