Copy files in folders from a Document Library to disk

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"
$destination = "L:OutputLocation" 
#derived right from the URL when viewing the folder, this works:
$web = Get-SPWeb -Identity $webUrl
function ProcessFolder 
$folder = $web.GetFolder($folderUrl)    
if (!$Folder.exists)
Write-Host -ForegroundColor DarkRed "Whoops, folder at source does not exist, please recheck"
$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)         
Write-Host "+" -NoNewline
foreach ($sf in $folder.SubFolders)
ProcessFolder($sf.url)  #Not quite Ackerman's function, this is first order recursion

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.

while (test-path $OutFileName)
$OutFileName=$destinationfolder + "/" + $inc+$JPName
Write-Host "!" -NoNewline -ForegroundColor DarkRed
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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