Thursday, 6 March 2014

PowerShell Script To download Bulk data from Document Library in SharePoint

Below Script Downloads All The Documents With all Sub folders of Document library. It also downloads CSV file which contains Metadata information of Downloaded documents. Also Catch block will Generate Error Log File .


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

$destination = "C:\\Test\\"
$web = Get-SPWeb -Identity "http://xyz:4444/"
$list = $web.GetList("http://xyz:4444/Shared 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
        try
        {
      
        $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()
         }
        catch
        {
        Write "Error: $file.name: $_" >>c:\logfile.txt
        continue;
        }
     
        }
}
$exportlist = @()
$list.Items | foreach {
$obj = New-Object PSObject -Property @{
"Title" = $_["Title"]
"Name" = $_["Name"]
"Modified Date" = $_["Modified"]
"Modified By" =$_["Modified By"]
"Size"= $_["File Size"]
"Path" = $web.Url + "/" + $_.File.Url
}
$exportlist += $obj
$exportlist | Export-Csv -path 'C:\Test\MyList.csv' -noType
}

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

No comments:

Post a Comment