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

Iron Contributor

Hi

 

I am trying to get the version of a file in a document library using PnP Powershell.

Connect-PnPOnline -Url <url> 

$ListItems = Get-PnPListItem -List <MyDocLibrary>

 

for each ($item in $ListItems)

{

        $file = $item.file

        $fileversions = $file.Versions

        Write-Host $file, $fileversions

 

}

 

But this does not seem to work.

 

Anybody any ideas ?

 

Thanks

 

Nigel

9 Replies

You can try this script

 

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

 

Hi @Manidurai Mohanamariappan

 

Works great (as long as you put the t on the end of Get-PnPContex !)

 

What about if I only want the latest version ?

 

Regards

 

Nigel

@Nigel Price something like the following should help you get started,  I have not tested this.

 

for (int i = versions.Count; i > 0; i--)
    {
       FileVersion version = file.Versions[i - 1];   
       string label = version.VersionLabel;
       string id = version.ID.ToString();
       string filename = Path.GetFileName(version.Url);
       string ext = Path.GetExtension(version.Url);
       string tmp1 = version.IsCurrentVersion;
       string tmp2 = version.Url;
    }

 

You can try this modified script 

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
}

@Nigel Price 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()
    }

@AlyaKoni Works like a charm, thank you!

@AlyaKoni  How could we also retrieve the CheckIn Comment for each version?