Sharepoint - Download and delete documents using Powershell

Since I don't see PowerShell script that downloads and deletes all files from document library to local or network drive in any of the answers I will post one (this script also keeps folder structure on destination drive):

Add-PSSnapin Microsoft.SharePoint.PowerShell

$destination = "C:\\test\\"
$web = Get-SPWeb -Identity "http://sharepoint2010/myweb/"
$list = $web.GetList("http://sharepoint2010/myweb/Shared%20Documents/")

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
    }
}

Permission issues? Just run it on SharePoint server as admin and it will work :)


I think that if you planing to create a timer job then better investigate how to do it using c# instead of powershell and when the code is running on a timer job it will use the farm account so you wont need to impersonate any account.

Here is a good example of moving/copying documents using the SharePoint object model http://geek.hubkey.com/2007/12/move-sharepoint-document-library-files.html

Hope this helps

Tags:

Powershell