Exporting documents from Sharepoint server to local disk


Here’s a Powershell script that finds documents stored in the Microsoft Sharepoint Server and exports them to local disk. The script finds all SPFile objects.

The SPFile objects are capable of representing files in a SharePoint Web sites that can be a Web Parts pages, items in a document libraries, or files in a folders.

The script has been tested on Microsoft Sharepoint Services 3, but it should work as well on Microsoft Sharepoint Server 2010.

[void][System.reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
[void][System.reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint.Utilities”)</span>

##################

$URL = "http://website";
$EXPORTDIR = "C:\export\";

##################

function script:Explore_Web($web)
{
Write-Host "*************** SITEWEB: " $web.Title "**************"

foreach($list in $web.Lists)
{
Explore_Items $list.Items
}

foreach($subweb in $web.Webs)
{
Explore_Web $subweb
}
}

function script:Explore_Items($items)
{
foreach($item in $items)
{
$file = $item.File

if( ($file -match '.doc$') `
-or ($file -match '.docx$') `
-or ($file -match '.xls$') `
-or ($file -match '.xlsx$') `
-or ($file -match '.ppt$') `
-or ($file -match '.pptx$') `
)
{
echo $file.Name;

Export_File $file $EXPORTDIR
}
}
}

function script:Export_File($file, $exportPath)
{
$filePath = Join-Path $exportPath $file.Name
$outPath = Set_Output_FileName($filePath)

Write_File $file $outPath
}

function script:Set_Output_FileName($path)
{
$ext = [System.IO.Path]::GetExtension($path)
$name = [System.IO.Path]::ChangeExtension($path, "")

$fileName = $path

$i = 0;
while(Test-Path $fileName)
{
$i++;
$fileName = $name+$i+$ext
}

return $fileName;
}

function script:Write_File($file, $filePath)
{
$fs = new-Object System.IO.FileStream($filePath, [System.IO.FileMode]::Create)
$bw = new-Object System.IO.BinaryWriter($fs);
[Byte[]] $binfile = $file.OpenBinary();
$bw.Write($binfile);
$bw.Close();
$fs.close();
}

##################
# MAIN SCRIPT #
##################

$site = new-Object Microsoft.SharePoint.SPSite($URL);

$siteweb = $site.OpenWeb();

foreach($web in $siteweb.Webs)
{
Explore_Web($web);
}

$web.Dispose();
$site.Dispose();

Write-Host "Done.";

Just a few remarks on the published code:

  • The variable $URL defines the server’s url address (line #6)
  • The variable $EXPORTDIR defines a local path where exported data will be stored (line #7)
  • This script connects to the Sharepoint Server and extracts uploaded Office documents only (the filter is defined in lines 32-37).
  • The script should be executed by user with administrative priviledges on the target Sharepoint server (the default authentication is used)

,

  1. No comments yet.
(will not be published)