Thursday, September 26, 2013

How To Download Documents From SharePoint To a File Server using Powershell



#Add SharePoint Snapin if not using SharePoint's PowerShell Console
if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin Microsoft.SharePoint.PowerShell
}
$destination = "c:\\test\\"
$web = Get-SPWeb -Identity "http://mysite/sites/demant/"
$list = $web.GetList("http://mysite/sites/demant/Documents")

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()
        #Delete file by deleting parent SPListItem
        #$list.Items.DeleteItemById($file.Item.Id)
    }
}

#Download root files
ProcessFolder($list.RootFolder.Url)
#Download files in folders
foreach ($folder in $list.Folders) {
    ProcessFolder($folder.Url)
}

#Delete folders
#foreach ($folder in $list.Folders) {
    #try {
       # $list.Folders.DeleteItemById($folder.ID)
    #}
   # catch {
        #Deletion of parent folder already deleted this folder
        #I really hate this
    #}

No comments:

Post a Comment