Copy files in folders from a Document Library to disk Copy files in folders from a Document Library to disk
Keyur Nathani

Keyur Nathani

October 15, 2012

All Post
Copy-files-in-folders-from-a-Document-Library-to-disk
Share:

Copy SharePoint files in folders to disk

A common request is extracting all the files within folders in a document library. The simple script below allows one to specify a source folder, library, web, and output location. The $TargetRootFolder can be found as a URL parameter in the URL when viewing the target folder for migrating. The script preserves the full URL structure including all folders and subfolders. Recursion makes this clean and simple.

 $webUrl = "http ://SharePoint/sites/MyWeb"
$TargetLib="MyLibrary"
$destination = "L:OutputLocation"
#derived right from the URL when viewing the folder, this works:
$TargetRootFolder="%2MyWeb%2SubFolder"
 
$web = Get-SPWeb -Identity $webUrl
 
function ProcessFolder 
{
    param($folderUrl)    
    $folder = $web.GetFolder($folderUrl)    
    if (!$Folder.exists)
    {
        Write-Host -ForegroundColor DarkRed "Whoops, folder at source does not exist, please recheck"
    }
    else
    {
 
    $destinationfolder = $destination + "/" + $folder.Url
 
    if (!(Test-Path -path $destinationfolder))         
    {             
        $dest = New-Item $destinationfolder -type directory          
    }   
 
    foreach ($file in $folder.Files) 
    {
    $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()  
    Write-Host "+" -NoNewline
    }
        foreach ($sf in $folder.SubFolders)
        {
            ProcessFolder($sf.url)  #Not quite Ackerman's function, this is first order recursion
        }   
    }
}
ProcessFolder($TargetRootFolder)

Now, if you need to ensure no documents ever overwrite, such as if you rename on the fly, here’s a bit of code that will cycle through optional filenames until one is found that does not exist.

 $inc=$null;
while (test-path $OutFileName)
{
$JPname="$($JPTitle)DUP$($inc)$($JPName.Substring($JPName.lastindexof(".")))"
$OutFileName=$destinationfolder + "/" + $inc+$JPName
$Inc++;
Write-Host "!" -NoNewline -ForegroundColor DarkRed
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to talk?

Drop us a line. We are here to answer your questions 24*7.