Friday 13 March 2015

Powershell for downloading files step by step from sharepoint document library

Below Powershell will download the file Test.pdf from List/Document library name "DocName" in Root folders named A,B and C (You can change the letters in powershell script).


if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$destination = "L:\Data\"
$web = Get-SPWeb -Identity "https://TestWebApp/"
$list = $web.GetList("https://TestWebApp/Test/DocName") #your List/Document Library path

function ProcessFolder
{
    param($folderUrl)
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files)
   
    {
   
         if($file.Name.Contains("Test.pdf"))
            {                                    
                 [Microsoft.SharePoint.SPFileVersion]$iv = $file.Versions[0];
                 $versionNumber = $iv.VersionLabel;    
                                   
             
               Write-Host    $versionNumber.Name
               if($versionNumber )
               {
             
               DownloadFile($iv)
               }
               else
               {
           
               DownloadFile($file)
               }
             }

      else
               {
         
               DownloadFile($file)
               }
                               

       
       }

    }
 

     Function DownloadFile($type)
     {
     try
     {
      $destinationfolder = $destination + "/" + $folder.Url
      if (!(Test-Path -path $destinationfolder))
        {
           $dest = New-Item $destinationfolder -type directory
         }

     $binary = $type.OpenBinary()
     $stream = New-Object System.IO.FileStream($destinationfolder + "/" + $file.Name), Create
     $writer = New-Object System.IO.BinaryWriter($stream)
     $writer.write($binary)
     $writer.Close()

     }
     Catch
     {
      Write "Error: $file.name: $_" >>"L:\Data\Error.txt"
      continue;
     }

     }
       
        #Ensure destination directory


function ProcessAllSubfolders($folderCollection)
{
    foreach ($folder in $folderCollection)
    {
        if ($folder.SubFolders.Count -gt 0)
        {
            ProcessAllSubfolders($folder.SubFolders)
        }

        ProcessFolder($folder.Url)
    }
}


#Download root files
#ProcessFolder($list.RootFolder.Url)
#Download files in folders

foreach($folder in $list.RootFolder.SubFolders)
{
if($folder.Name.StartsWith("A") -or $folder.Name.StartsWith("B") -or $folder.Name.StartsWith("C"))
{
ProcessFolder($folder.Url)

if ($folder.Subfolders.Count -gt 0)
        {
            ProcessAllSubfolders($folder.SubFolders)
        }

}

}

Write-Host "Completed Succesfully"


 
 

3 comments: