Backup documents from document library with PowerShell script

This is a PowerShell script to download all documents from a document library to the file system.
If $majorVersionsOnly is FLASE it will download the latest version of all the documents including the documents with no published versions.
If $majorVersionsOnly is TRUE it will download all documents that have published versions(their last major version will be downloaded). For example if Document1.docx’s latest version is 4.2 with $majorVersionsOnly=$true the script will download version 4.0 of Document1.docx. With $majorVersionsOnly=$false the script will download version 4.2 of Document1.docx.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$siteUrl = 'http://....'
$listUrl = 'http://....'
$folderPath = 'C:\\....'
$majorVersionsOnly = $true;

Function GetFileBinary([Microsoft.SharePoint.SPListItem]$_item)
{
    $_binary = $null;
    $_lastVersion = $_item.Versions[0].VersionLabel;
    $_splitted = $_lastVersion.Split('.');
    $_lastMajor = [int]$_splitted[0];
    $_lastMinor = [int]$_splitted[1];

    if ($majorVersionsOnly)
    {
        if ($_item.HasPublishedVersion)
        {
            if ($_lastMinor -eq 0)
            {
                $_binary = $_item.File.OpenBinary();
            }
            else
            {
                $_fileVersions = $_item.File.Versions;
                $_fileVersion = $_fileVersions.GetVersionFromLabel($_lastMajor.ToString() + ".0");
                $_binary = $_fileVersion.OpenBinary();
            }
        }
    }
    else
    {
        $_binary = $_item.File.OpenBinary();
    }

    return $_binary;
}
  
$web = Get-SPWeb -Identity $siteUrl
$list = $web.GetList($listUrl)
$items = $list.Items
ForEach ($item in $items)
{
    $binary = GetFileBinary($item);
    $folderPathToSave = $folderPath + "\\" + $item.Name;
    if ($binary -ne $null)
    {
        $stream = New-Object System.IO.FileStream($folderPathToSave,[System.IO.FileMode]::Create,[System.IO.FileAccess]::ReadWrite);
        $writer = New-Object System.IO.BinaryWriter($stream);
        $writer.Write($binary);
        $writer.Close();
    }
}
     
$web.Dispose()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: