Microsoft cloud engineer - SharePoint, Office 365, Azure, DotNet, Angular, JavaScript.
Microsoft cloud engineer - SharePoint, Office 365, Azure, DotNet, Angular, JavaScript.

PowerShell – download all files in a Document Library

I needed to download the full contents of a Document Library to a local folder.   Explorer View, SharePoint Designer, and WebDAV simply weren’t fast enough for the large number of items needed.  So I wrote a quick script:

PowerShell – SOM (Server Object Model)

$s = Get-SPSite “http://sp2013”
$files = $s.RootWeb.GetFolder("Shared Documents").Files
foreach ($file in $files) {
    Write-host $file.Name
    $b = $file.OpenBinary()
    $fs = New-Object System.IO.FileStream(("d:\temp\"+$file.Name), [System.IO.FileMode]::Create)
    $bw = New-Object System.IO.BinaryWriter($fs)
    $bw.Write($b)
    $bw.Close()
}

PowerShell – Remote HTTP (Client Side / Office 365)

# Download all files from a SharePoint Document Library view to the local folder over HTTP remotely.  
# No server side requirement, can run anywhere, including end user desktops.

param (
    $url,       # "http://portal/sites/test",
    $listID,    # "41E5FC8E-D174-4F48-AC3C-79F999A045D1",
    $viewID     # "5E9415B3-3C63-48AD-9DC2-A5A282B61790"
    )

# Current folder
$scriptpath = Split-Path $MyInvocation.MyCommand.Path
	
# Open file list
Write-Host "Opening $url"
$ows = "$url/_vti_bin/owssvr.dll?Cmd=Display&List={$listID}&View={$viewID}&XMLDATA=TRUE"
$owsList = "$url/_vti_bin/owssvr.dll?Cmd=ExportList&List={$listID}&XMLDATA=TRUE"
$r = Invoke-WebRequest $ows -UseDefaultCredentials
$rList = Invoke-WebRequest $owsList -UseDefaultCredentials
$xml = $r.Content
$xmlList = $rList.Content
$folder = $xmlList.List.Url

# Client
$client = New-Object System.Net.WebClient
$client.UseDefaultCredentials = $true

# Loop and download
foreach ($row in $xml.xml.data.row) {
    $name = $row.ows_LinkFilename
    $from = "$url/$folder/$name"
    $client.DownloadFile($from, "$scriptpath\$name")
}

Write-Host "DONE"

NOTE – Remote HTTP (Client Side / Office 365) can recurse files from all sub-folders by updating the View to “Show all items (all folders)”

References

© Copyright 2016
@ SPJeff

Return to Top ▲Return to Top ▲