Thursday, September 25, 2014

PowerShell Script to download SharePoint List attachments


Here is a PowerShell script for downloading SharePoint List Item attachments. When the code is run all attachments are downloaded. Subfolders are created based on the Assigned To.


$webUrl = "Your Site Name"
$listname = "Your List Name"
$tempLocation = "Folder Location"
$site = new-object Microsoft.SharePoint.SPSite($webUrl)
$web = $site.OpenWeb()
$list = $web.Lists[$listname]
foreach ($listItem in $list.Items)
{
$listItem["Assigned To"].ToString();
$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$listItem["Assigned To"].ToString());
$userfield.User.DisplayName;
Write-Host " Content: " $userfield.User.DisplayName;
$destinationfolder = $tempLocation + "\" + $userfield.User.DisplayName;
if (!(Test-Path -path $destinationfolder))
{
$dest = New-Item $destinationfolder -type directory
}
foreach ($attachment in $listItem.Attachments)
{
$file = $w.GetFile($listItem.Attachments.UrlPrefix + $attachment)
$bytes = $file.OpenBinary()
$path = $destinationfolder + " \" + $attachment
Write " Saving $path"
$fs = new-object System.IO.FileStream($path, " OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()
}
}

No comments:

Post a Comment