Tìm kiếm trang web

SharePoint Online: Xóa lịch sử phiên bản bằng PnP PowerShell


Yêu cầu: Xóa lịch sử phiên bản trong SharePoint Online.

Làm cách nào để xóa phiên bản trong SharePoint Online?

Nếu bạn đã quản lý SharePoint Online một thời gian thì bạn biết rằng việc giữ cho môi trường của mình sạch sẽ và ngăn nắp là điều cần thiết. Một cách để dọn dẹp là xóa các phiên bản tài liệu và tệp cũ hơn vì các phiên bản cũ có thể chiếm nhiều dung lượng lưu trữ. Bài đăng trên blog này sẽ chỉ cho bạn cách xóa các phiên bản tài liệu cũ hơn trong SharePoint Online bằng PowerShell và tự động hóa quy trình dọn dẹp.

Để xóa các phiên bản trước của tệp trong SharePoint Online, hãy làm theo các bước sau:

  1. Điều hướng đến thư viện tài liệu SharePoint Online của bạn, chọn tệp và nhấp vào “Lịch sử phiên bản” từ thanh công cụ. (hoặc Chọn “Lịch sử phiên bản” từ menu ngữ cảnh của tài liệu)
  2. Trên trang lịch sử phiên bản, Bạn có thể chọn “Xóa” từ menu ngữ cảnh của phiên bản cụ thể. Để xóa tất cả phiên bản của một tài liệu hoặc mục danh sách, hãy nhấp vào liên kết “Xóa tất cả phiên bản” trên trang Lịch sử phiên bản rồi xác nhận lời nhắc.

Xóa tất cả các phiên bản của tệp bằng PnP PowerShell

Lịch sử phiên bản SharePoint Online giúp theo dõi các thay đổi được thực hiện đối với tài liệu. Tuy nhiên, đôi khi có thể cần phải xóa lịch sử phiên bản để giải phóng dung lượng lưu trữ hoặc vì mục đích tuân thủ. Hãy xem cách xóa lịch sử phiên bản trong SharePoint Online bằng PowerShell.

Dưới đây là cách xóa tất cả các phiên bản của tệp trong thư viện tài liệu SharePoint Online bằng PowerShell:


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$FileURL= "/sites/marketing/Branding/Invoice.xlsx"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
 
#Get all versions of the File
$Versions = Get-PnPFileVersion -Url $FileURL

#Delete all versions of the File
$Versions.DeleteAll()
Invoke-PnPQuery

SharePoint Online: Xóa lịch sử phiên bản bằng PnP PowerShell

Hãy xóa tất cả phiên bản của tất cả các mục trong danh sách hoặc thư viện bằng PowerShell.


#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"
$ListName="Documents"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get the Context
$Ctx= Get-PnPContext

#Get All Items from the List - Exclude 'Folder' List Items
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 | Where {$_.FileSystemObjectType -eq "File"}

ForEach ($Item in $ListItems)
{
    #Get File Versions
    $File = $Item.File
    $Versions = $File.Versions
    $Ctx.Load($File)
    $Ctx.Load($Versions)
    $Ctx.ExecuteQuery()
    Write-host -f Yellow "Scanning File:"$File.Name
    
    If($Versions.Count -gt 0)
    {
        #Delete all versions
        $Versions.DeleteAll()
        $Ctx.ExecuteQuery()
        Write-Host -f Green "Deleted All Previous Versions of the File:"$File.Name
    }
}

Chúng tôi có thể xóa tất cả các phiên bản trước của tất cả các tệp trong thư viện tài liệu SharePoint Online bằng PnP PowerShell dưới dạng:


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/IC"
$LibraryName = "Energy"
 
Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive

    #Get the Library
    $Library = Get-PnPList -Identity $LibraryName 
    $global:counter=0

    #Get All Items from the List - Get 'Files
    $ListItems = Get-PnPListItem -List $Library -Fields FileLeafRef,FileRef -PageSize 2000 -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress `
                    -PercentComplete ($global:Counter / ($Library.ItemCount) * 100) -Activity "Getting Files of '$($Library.Title)'" `
                       -Status "Processing Files $global:Counter of $($Library.ItemCount)";} | Where {($_.FileSystemObjectType -eq "File")} 
    Write-Progress -Activity "Completed Retrieving Files!" -Completed

    #Loop through each file
    $global:counter=1
    ForEach ($Item in $ListItems)
    {
        #Get File and File Versions
        $Versions = Get-PnPFileVersion -Url $Item.FieldValues.FileRef
        Write-host -f Yellow "Scanning File ($global:counter of $($Library.ItemCount)) : $($Item.FieldValues.FileRef)"
      
        If($Versions.Count -gt 0)
        {
            #Delete all versions
            $Versions.DeleteAll()
            Invoke-PnPQuery
            Write-Host -f Green "`tDeleted All Previous Versions of the File!" #"$Item.FieldValues.FileRef
        }
        $global:counter++
    }
}
Catch {
    write-host -f Red "Error Cleaning up Version History!" $_.Exception.Message
}

PowerShell để xóa các phiên bản trước theo thư mục

Đây là một cách tiếp cận khác để xóa các phiên bản trước của tất cả các tệp trên thư viện có ít hơn 5000 mục.


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName ="Documents"

#Function to Clear all File versions in a Folder
Function Cleanup-Versions([Microsoft.SharePoint.Client.Folder]$Folder)
{
    Write-host "Processing Folder:"$Folder.ServerRelativeUrl -f Yellow
    #Get the Site Relative URL of the folder
    $FolderSiteRelativeURL = $Folder.ServerRelativeURL.Replace($Web.ServerRelativeURL,[string]::Empty)

    #Get All Files from the folder    
    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File
    
    #Iterate through each file
    ForEach ($File in $Files)
    {
        #Get File Versions
        $Versions = Get-PnPProperty -ClientObject $File -Property Versions 
        Write-host -f Yellow "`tScanning File:"$File.Name
     
        If($Versions.Count -gt 0)
        {
            #Delete all versions
            $Versions.DeleteAll()
            Invoke-PnPQuery
            Write-Host -f Green "`t`tDeleted All Previous Versions of the File:"$File.Name
        }
    }

    #Get Sub-folders from the folder - Exclude "Forms" and Hidden folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder | Where {($_.Name -ne "Forms") -and (-Not($_.Name.StartsWith("_")))}
    Foreach($SubFolder in $SubFolders)
    {
        #Call the function recursively
        Cleanup-Versions -Folder $SubFolder     
    }
}
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
$Web = Get-PnPWeb

#Get the Root Folder of the Library
$RootFolder = Get-PnPList -Identity $LibraryName -Includes RootFolder | Select -ExpandProperty RootFolder

#Call the function with Root Folder of the Library
Cleanup-Versions -Folder $RootFolder

Bạn có thể dọn sạch các phiên bản trước của tất cả các tệp khỏi một thư mục bằng cách thay thế Dòng #45 bằng “$RootFolder=Get-PnPFolder -Url $FolderServerRelativeURL”.

Giữ năm phiên bản cuối cùng và xóa phần còn lại:

Đi qua trang lịch sử phiên bản và xóa từng cái một thật là cồng kềnh. Đây là PnP PowerShell để giữ các phiên bản 'N' cuối cùng và xóa tất cả các phiên bản khác.


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Funds"
$ListName = "Documents"
$VersionsToKeep = 5
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin

#Get the Document Library
$List = Get-PnPList -Identity $ListName
 
#Get the Context
$Ctx= Get-PnPContext

$global:counter=0 
#Get All Items from the List - Get 'Files
$ListItems = Get-PnPListItem -List $ListName -Fields FileLeafRef -PageSize 2000 -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress `
                -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity "Getting Files of '$($List.Title)'" `
                    -Status "Processing Files $global:Counter of $($List.ItemCount)";} | Where {($_.FileSystemObjectType -eq "File")}
Write-Progress -Activity "Completed Retrieving Files!" -Completed

$TotalFiles = $ListItems.count
$Counter = 1 
ForEach ($Item in $ListItems)
{
    #Get File Versions
    $File = $Item.File
    $Versions = $File.Versions
    $Ctx.Load($File)
    $Ctx.Load($Versions)
    $Ctx.ExecuteQuery()
 
    Write-host -f Yellow "Scanning File ($Counter of $TotalFiles):"$Item.FieldValues.FileRef
    $VersionsCount = $Versions.Count
    $VersionsToDelete = $VersionsCount - $VersionsToKeep
    If($VersionsToDelete -gt 0)
    {
        write-host -f Cyan "`t Total Number of Versions of the File:" $VersionsCount
        $VersionCounter= 0
        #Delete versions
        For($i=0; $i -lt $VersionsToDelete; $i++)
        {
            If($Versions[$VersionCounter].IsCurrentVersion)
            {
                $VersionCounter++
                Write-host -f Magenta "`t`t Retaining Current Major Version:" $Versions[$VersionCounter].VersionLabel
                Continue
            }
            Write-host -f Cyan "`t Deleting Version:" $Versions[$VersionCounter].VersionLabel
            $Versions[$VersionCounter].DeleteObject()
        }
        $Ctx.ExecuteQuery()
        Write-Host -f Green "`t Version History is cleaned for the File:"$File.Name
    }
    $Counter++
}

Làm cách nào để xóa lịch sử phiên bản cho tất cả thư viện tài liệu trên một trang web?


#Config Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$VersionsToKeep = 5

Try { 
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive

    #Get the Context
    $Ctx= Get-PnPContext

    #Exclude certain libraries
    $ExcludedLists = @("Form Templates", "Preservation Hold Library","Site Assets", "Pages", "Site Pages", "Images",
                            "Site Collection Documents", "Site Collection Images","Style Library")

    #Get All document libraries
    $DocumentLibraries = Get-PnPList | Where-Object {$_.BaseType -eq "DocumentLibrary" -and $_.Title -notin $ExcludedLists -and $_.Hidden -eq $false}

    #Iterate through each document library
    ForEach($Library in $DocumentLibraries)
    {
        Write-host "Processing Document Library:"$Library.Title -f Magenta

        #Get All Items from the List - Exclude 'Folder' List Items
        $ListItems = Get-PnPListItem -List $Library -PageSize 2000 | Where {$_.FileSystemObjectType -eq "File"}

        #Loop through each file
        ForEach ($Item in $ListItems)
        {
            #Get File Versions
            $File = $Item.File
            $Versions = $File.Versions
            $Ctx.Load($File)
            $Ctx.Load($Versions)
            $Ctx.ExecuteQuery()
 
            Write-host -f Yellow "`tScanning File:"$File.Name
            $VersionsCount = $Versions.Count
            $VersionsToDelete = $VersionsCount - $VersionsToKeep
            If($VersionsToDelete -gt 0)
            {
                write-host -f Cyan "`t Total Number of Versions of the File:" $VersionsCount
                $VersionCounter= 0
                #Delete versions
                For($i=0; $i -lt $VersionsToDelete; $i++)
                {
                    If($Versions[$VersionCounter].IsCurrentVersion)
                    {
                       $VersionCounter++
                       Write-host -f Magenta "`t`t Retaining Current Major Version:"$Versions[$VersionCounter].VersionLabel
                       Continue
                    }
                    Write-host -f Cyan "`t Deleting Version:" $Versions[$VersionCounter].VersionLabel
                    $Versions[$VersionCounter].DeleteObject()
                }
                $Ctx.ExecuteQuery()
                Write-Host -f Green "`t Version History is cleaned for the File:"$File.Name
            }
        }
    }
}
Catch {
    write-host -f Red "Error Cleaning up Version History!" $_.Exception.Message
}

Bạn có thể áp dụng tính năng dọn dẹp này cho tất cả các tệp trong một thư mục hoặc thư mục con cụ thể bằng cách:


$ListItems = Get-PnPListItem -List $ListName -FolderServerRelativeUrl $FolderServerRelativeURL -PageSize 2000

Tập lệnh này để lại số phiên bản 'N' gần đây và xóa tất cả các phiên bản trước đó của tài liệu. Để dọn sạch các phiên bản cũ hơn trong SharePoint Online bằng PowerShell CSOM, hãy tham khảo: SharePoint Online: Xóa lịch sử phiên bản bằng PowerShell CSOM

Đừng quên đặt giới hạn cho số lượng phiên bản trong: Cài đặt danh sách/thư viện >> Cài đặt lập phiên bản để ngăn bất kỳ phiên bản nào phát triển vượt quá giới hạn của bạn.

Phần kết luận:

Tóm lại, việc xóa lịch sử phiên bản trong SharePoint Online có thể cần thiết vì nhiều lý do, bao gồm giải phóng dung lượng lưu trữ và mục đích tuân thủ. Mặc dù có thể xóa lịch sử phiên bản theo cách thủ công nhưng đây có thể là một quá trình tốn thời gian, đặc biệt nếu bạn có số lượng lớn tài liệu. Tuy nhiên, việc sử dụng PowerShell có thể giúp quá trình này hiệu quả và đơn giản hơn. Với tập lệnh được cung cấp trong hướng dẫn này, bạn có thể dễ dàng xóa lịch sử phiên bản trong SharePoint Online chỉ bằng vài bước. Bằng cách tự động hóa tác vụ này, bạn có thể tiết kiệm thời gian quý báu và đảm bảo rằng môi trường SharePoint Online luôn được tổ chức và tối ưu hóa cho nhu cầu của bạn.

Bài viết liên quan