2

Is it possible to download all versions of a file with PnP? (with Get-PnPFile I guess, targeting SharePoint-2013)

The closest I've found was with help of how-do-i-get-the-version-of-a-file-using-pnp-powershell, but I'm stuck on downloading the versions.

$ctxt= Get-PnPContext
Get-PnPListItem -List <a Document Library> `
    | Where-Object { $_.FieldValues.Title -eq "a title" } ` # a requirement
    | Foreach-Object { 
        $f = $_.file; 
        $versions = $f.versions; 
        $ctxt.Load($f); 
        $ctxt.Load($fvs); 
        $ctxt.ExecuteQuery();
        foreach ($v in $versions){ 
           $v.Url
   }
}

The URLs are like _vti_history/<versionLabel>/<path/to/file>, is it possible to download these URLs or is there a more direct PnP solution?

2 Answers 2

2

You can use the below PnP PowerShell code:

Connect-PnPOnline -Url <url> 
$ListItems = Get-PnPListItem -List <MyDocLibrary>
$ctx= Get-PnPContext
foreach ($item in $ListItems)
{
        $file = $item.file
        $ctx.load($file)
        $ctx.ExecuteQuery()
        Write-Host $file.Name,$file.UIVersionLabel
}

Source of the above code:

How Do I get the version of a file using PnP Powershell

Other Approaches:

Download all version of a file using the PowerShell and SharePoint web service (Versions.asmx):

# ******* Variables Section ******************
#Define these variables 
$WebURL="http://sharepoint.crescent.com/sites/Operations/"
$FilePath ="http://sharepoint.crescent.com/sites/Operations/docs/designDoc.docx"
$TargetFolder = "C:\Downloads"
# *********************************************

#Web Service URL
$WebServiceURL =$WebURL+"_vti_bin/Versions.asmx"
$WebService = New-WebServiceProxy -Uri $WebServiceURL -UseDefaultCredential
$WebService.URL=$WebServiceURL

#Get File name from file path
$FileName = $FilePath.Substring($FilePath.LastIndexOf("/")+1,($FilePath.Length-$FilePath.LastIndexOf("/")-1))

#Create the Target Library if it doesn't exists
    if (!(Test-Path -path $TargetFolder))
       {   
             #If it doesn't exists, Create
             $TargetFolder = New-Item $TargetFolder -type directory
       }


#Call web service method "GetVersions" to retrieve versions collection
$FileVersions = $WebService.GetVersions($FilePath).Result
 foreach($File in $FileVersions)
 { 
  #Frame the File name : E.g. 1.0_Filename.ext
  $VersionFileName = "$($TargetFolder)\$($File.version)_$($FileName)"
  write-host $VersionFileName
  $webclient = New-Object System.Net.WebClient
     $webclient.UseDefaultCredentials = $true
  write-host $File.url
     $webclient.DownloadFile($File.url,$VersionFileName)
  Write-Host "Downloaded version: $($File.Version)"
 }

Source of the above code:

Download All Versions of a Document in SharePoint using PowerShell - Web Services

Download all versions of a file using the SharePoint PowerShell server object model:

 Get-PSSnapin -Registered
 if(-not (Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue)){Add-PSSnapin "Microsoft.SharePoint.PowerShell"}

$spSiteURL = "https://intranet.contoso.com/sites/jayant/"
$spWeb = Get-SPWeb -Identity $spSiteURL
$spDocFolder = $spWeb.GetFolder("Docs")
$spFileCollection = $spDocFolder.Files
$dlProps = @{
    DownloadURL = ''
    DownloadFileName = ''
}
$dlobjects = @()
ForEach($file in $spFileCollection){
$spFileVersionCollection= $file.Versions;
#===============get URLs of old versions===============
    if ($spFileVersionCollection) {
         ForEach($version in $spFileVersionCollection){
            $downloadversURL = $version.Url;
            $dlobject = New-Object -TypeName PSObject -Property $dlProps
            $dlobject.DownloadURL=$downloadversURL;
            $dlobject.DownloadFileName = $version.VersionLabel + "_" +$file.Name;
           $dlobjects +=$dlobject;
         }
    }
#===============get URLs of old versions===============

#================get URLs of latest versions==========
    $downloadlatestURL = $file.Url;
    $dlobject = New-Object -TypeName PSObject -Property $dlProps
    $dlobject.DownloadFileName = "Latest" + $file.UIVersionLabel + "_" +$file.Name;
   $dlobject.DownloadURL=$downloadlatestURL;
    $dlobjects +=$dlobject;
#================get URLs of latest versions==========
}
#================download version files================
$destination="C:\Users\jayant\Desktop\version files\"
$webclient = New-Object System.Net.WebClient
$webclient.UseDefaultCredentials = $true
ForEach($dlobj in $dlobjects){
    $fullURL = $spSiteURL + $dlobj.DownloadURL;
    $destinationFullPath=$destination + $dlobj.DownloadFileName;
    $webclient.DownloadFile($fullURL, $destinationFullPath);
}
#================download version files================

Source of the above code:

Download all File Versions from SharePoint

7
  • Thank you for your long response. Unfortunately it doesn't answer fully my question. The first approach is the one I had cited in my question from the Microsoft community site. It provides the versionLabels but how to download the content of all these versions? I cannot make the web service way for some reasons, and the last one from Kalmstrom is not accessible for me as I'm just a site collection admin, not a SP admin. I cannot install Get-SPWeb as it's in SharePoint Server Module (if I am wrong, please tell me how).
    – tebans
    Apr 14, 2020 at 8:33
  • My question is related to this question from 2017 how-to-download-fileversion-content-from-sharepoint-online-using-csom. I don't understand it anyway,..
    – tebans
    Apr 14, 2020 at 8:37
  • You can use the Get-SPWeb, being a site collection administrator for that before executing the script at the beginning of script, we need to add this line : Add-PSSnapin Microsoft.Sharepoint.Powershell and this script Get-SPWeb has to be executed in any of the SharePoint server.
    – SP 2022
    Apr 14, 2020 at 8:41
  • I tried this command in the past, but I've always bumped into a cryptic result: Add-PSSnapin -Name Microsoft.Sharepoint.Powershell Add-PSSnapin : Aucun composant logiciel enfichable n'a été inscrit pour Windows PowerShell version 5. Au caractère Ligne:1 : 1 + Add-PSSnapin -Name Microsoft.Sharepoint.Powershell + ~ + CategoryInfo : InvalidArgument : (Microsoft.Sharepoint.Powershell:String) [Add-PSSnapin], PSArgumentExc eption + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand and Get-PSSnapin -Registered is empty. `
    – tebans
    Apr 14, 2020 at 9:15
  • Sorry for the sentence Aucun composant logiciel enfichable n'a été inscrit pour Windows PowerShell version 5 in French. I don't know how to translate accurately. Is it No snap-ins have been registered for Windows PowerShell version 5.?. I've read I could use Import-Module instead, but with no success.
    – tebans
    Apr 14, 2020 at 9:20
1

For SharePoint Online I'm using following code:

    Get-PnPFile -Url $item.ServerRelativeUrl -Path $destinationFolderPath -AsFile -Force # Latest version
    $ctx= Get-PnPContext
    $ctx.Load($item.Versions)
    $ctx.ExecuteQuery()
    foreach ($version in $item.Versions)
    {
        $versionValue = $version.VersionLabel
        $str = $version.OpenBinaryStream()
        $ctx.ExecuteQuery()
        $filename =  (Split-Path $item.ServerRelativeUrl -Leaf) + "." + $versionValue
        $filepath = Join-Path $destinationFolderPath $filename
        $fs = New-Object IO.FileStream $filepath ,'Append','Write','Read'
        $str.Value.CopyTo($fs) # Older version
        $fs.Close()
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.