SharePoint 2010 Powershell Copy List Item Attachments into Document Library Folders!

Check this out – you have a giant SharePoint list, packed full of attachments. This script will create a document library folder for each list item, then copy the attachments from the list item into the designated document library folder. After you run the script, you can disable attachments in the list settings, or run another Powershell to delete the attachments. I love Powershell!

$web=Get-SPWeb "http://sharepoint/sites/abc"
$list=$web.Lists.TryGetList("Item Documents")
$trackinglist = $web.lists["Tracking List"]
$items = $trackinglist.items
foreach($item in $items)
$title = $item.title
$folderItem = $list.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,"$title")
$folderItem["Title"] = "$title"
$attachments = $item.Attachments
$progress ++

if($attachments.count -gt 0)
foreach($leafName in $attachments)
$spFile = $$trackinglist.ParentWeb.GetFile($item.Attachments.UrlPrefix + $leafName)
$targetFile = $folderItem.Folder.Url + "/" + $spFile.Name
$dList = [Microsoft.Sharepoint.SPFolder]$web.GetFolder($folderItem.Folder.Url)
$dLibrary = $web.Lists[$dList.ContainingDocumentLibrary]
$sbytes = $spFile.OpenBinary()
$dFileName = $dList.Files.Add($targetFile, $sbytes, $true)

$docUrl = "/sites/abc/" + $folderItem.Folder.Url + "/, $title"
$item["Item Documents"] = $docUrl

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s