Skip to content

Instantly share code, notes, and snippets.

@OlafD
Last active November 21, 2020 15:58
Show Gist options
  • Save OlafD/5286bcbe330baee430b0663069ca5430 to your computer and use it in GitHub Desktop.
Save OlafD/5286bcbe330baee430b0663069ca5430 to your computer and use it in GitHub Desktop.
For a document by its item id download all versions incl. the current.
param (
[string]$Url,
[string]$Listname,
[int]$ItemId,
$Credentials,
[string]$DownloadFolder
)
if ($Credentials -eq $null)
{
$Credentials = Get-Credential
}
Connect-PnPOnline -Url $Url -Credentials $Credentials
$item = Get-PnPListItem -List $Listname -Id $ItemId
$versionString = $item["_UIVersionString"]
$createdCurrent = $item["Modified"].ToString("dd.MM.yyyy-HH:mm:ss") # when this version was created ;-)
$createdByTitleCurrent = $item["Author"].LookupValue
$createdByEmailCurrent = $item["Author"].Email
$filename = $item["FileLeafRef"]
$fileUrl = $item["FileRef"]
$fileHistoryFile = $DownloadFolder + "\History for " + $filename + ".txt"
"Version;Created;CreatedBy;CreatedByEmail" | Out-File -FilePath $fileHistoryFile -Force
Get-PnPFile -Url $fileUrl -Path $DownloadFolder -Filename ($versionString + " - " + $filename) -AsFile -Force
$fileVersionCollection = Get-PnPFileVersion -Url $fileUrl
foreach ($fileVersion in $fileVersionCollection)
{
$createdBy = Get-PnPProperty -ClientObject $fileVersion -Property CreatedBy
$createdByTitle = $createdBy.Title
$createdByEmail = $createdBy.Email
$versionLabel = $fileVersion.VersionLabel
$created = $fileVersion.Created.ToString("dd.MM.yyyy-HH:mm:ss")
"$versionLabel;$created;$createdByTitle;$createdByEmail" | Out-File -FilePath $fileHistoryFile -Append
Write-Host $versionLabel
$stream = $fileVersion.OpenBinaryStream()
Invoke-PnPQuery
$downloadFile = $DownloadFolder + "/" + ($versionLabel + " - " + $filename)
$fileStream = New-Object System.IO.FileStream($downloadFile, [System.IO.FileMode]::OpenOrCreate)
$stream.Value.CopyTo($fileStream)
$fileStream.Dispose()
}
Write-Host $versionString
"$versionString;$createdCurrent;$createdByTitleCurrent;$createdByEmailCurrent" | Out-File -FilePath $fileHistoryFile -Append
Write-Host "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment