5

Using Powershell, I have to get the total size of all attached files on all list items for a generic list. I tried using the function below but this displays the total length of names for the attached files.

function GetListSize($List)
{
    [long]$listSize = 0                 

    foreach ($listItem in $List.Items)
    {                   
        $listItemAttachments = $listItem.Attachments 
        foreach($file in $listItemAttachments) 
        {            
            $listSize +=  $file.Length 
        }
    }

    $totalInMb = ($listSize/1024)/1024
    $totalInMb = "{0:N2}" -f $totalInMb

    return $totalInMb    
}

I can do this using C# code (How to get size of SharePoint 2010 list item attachment?). How can I do this using Powershell?

6

SPAttachmentCollection stores only file names. To get actual files, you should retrieve files with these names from folder $List.RootFolder.SubFolders["Attachments"].SubFolders[$listItem.ID].

So, you should use this code:

function GetListSize($List)
{
    [long]$listSize = 0
    $allAttachmentsFolder = $List.RootFolder.SubFolders["Attachments"]

    foreach ($listItem in $List.Items)
    {                   
        $listItemAttachments = $listItem.Attachments
        $attachmentsFolder = $allAttachmentsFolder.SubFolders[$listItem.ID]
        foreach($file in $listItemAttachments) 
        {            
            $listSize += $attachmentsFolder.Files[$file].Length
        }
    }

    $totalInMb = ($listSize/1024)/1024
    $totalInMb = "{0:N2}" -f $totalInMb

    return $totalInMb    
}
| improve this answer | |
  • eh, thx I will test it now... – Ciprian Grosu May 13 '11 at 8:00
  • 1
    I think, you even could try to walk through all the $list.RootFolder.SubFolders["Attachments"].SubFolders, and count all files size in each of them. This should be a little bit faster. – Andrey Markeev May 13 '11 at 8:05
  • I receive an error on this line $allAttachmentsFolder = $List.RootFolder.SubFolder[ <<<< "Attachments"] but anyway I made it work using this $attachmentsFolder = $Web.Folders["Lists"].SubFolders[$list.Title].SubFolders["Attachments"].SubFolders[$listItem.Id] and of cource I send the Web as parameter to the function also ... I will try your last suggestion also. THX – Ciprian Grosu May 13 '11 at 8:16
  • ok, fix it the correct line was $allAttachmentsFolder = $List.RootFolder.SubFolders["Attachments"] aka SubFolers instead of SubFolder :) BIG THX – Ciprian Grosu May 13 '11 at 8:20
  • I fixed the answer, it was a kind of typo, sorry :( P.S. You should upvote and accept the answer if it helped you, to make people see that it is correct. – Andrey Markeev May 13 '11 at 8:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.