Friday, September 11, 2015

Download Files/Images from SharePoint Libraries using PowerShell

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.

No comments:

Post a Comment