Download Files/Images from SharePoint Libraries using PowerShell


I consigned a task to backup all files inside different document libraries of a SharePoint site on hard disk. We need to reorganize the entire site and this site comprises so many document libraries. So downloading documents one by one is a gigantic task as the site has gigs of docs. Alternative option is to open libraries in explorer and start copying them to a place, but this methodology has so many limitations e.g. network speed, installation of office components, much time required etc.
I want to get this job done hastily. So for a moment I thought of Power Shell. I want to give it a try and trust me by using this I was able to download gigs of documents within minute. Below is the code snippet for your reference:

 

######################## Start Variables ########################
######################## Download Files Script######################
$destination = $args[0]
$webUrl = $args[1]

##############################################################
# Replace actual document libraries name with DocLib1, 2, 3 etc.
$listUrls=”DocLib1″,”DocLib2″,”DocLib3″,”DocLib4″,”DocLib5″

$web = Get-SPWeb -Identity $webUrl

foreach($listUrl in $listUrls)
{
$list = $web.GetList($webUrl+”/”+$listUrl)

function ProcessFolder {
    param($folderUrl)
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files) {
        #Ensure destination directory
        $destinationfolder = $destination + “/” + $folder.Url
        if (!(Test-Path -path $destinationfolder))
        {
            $dest = New-Item $destinationfolder -type directory
        }
        #Download file
        $binary = $file.OpenBinary()
        $stream = New-Object System.IO.FileStream($destinationfolder + “/” + $file.Name), Create
        $writer = New-Object System.IO.BinaryWriter($stream)
        $writer.write($binary)
        $writer.Close()
        }
}

#Download root files
ProcessFolder($list.RootFolder.Url)
#Download files in folders
foreach ($folder in $list.Folders) {
    ProcessFolder($folder.Url)
}}

 

Copy this to a notepad file and save with extension .ps1 E.g. DownloadFiles.ps1

Open SharePoint Management Shell 2010; navigate to the path of script. Provide destination path as argument 1 and site URL as argument 2 as shown below.  

.\DownloadFiles.ps1 “d:\documents” http://mySite

*This will create separate folders for each document library with library name.

 

Advertisements

Leave a Comment

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