SharePoint PowerShell Script Series Part 4–Gathering item count for all document libraries in a Site Collection


I apologize it’s been so long since I’ve published any new blog content.  I recently moved into a new position in Microsoft as a Premier Field Engineer.  I’m really enjoying it so far and will start pumping out new blog content soon.  For now, I recently wrote a PowerShell script which fetches the item count for items that reside in all Document Libraries for a given Site Collection.  That includes all Document Libraries that exists in both the root site and all sub sites. 

The script will produce the following output:

1.    Total # of Document Libraries with 0 items
2.     Total # of Document Libraries with 1 or more items
2.    Total # of items in all Document Libraries
3.    Total # of items in DocLib\Subfolders
4.     Start Time and End Time of Script

 

Instructions for running the script:  
 
1.    Copy the below script and save it in notepad
2.    Save it with a anyfilename.ps1 extension
3.    To run, copy the file to a SharePoint Server
4.    Select Start\Microsoft SharePoint 2010 Products\SharePoint 2010 Management Shell
5.    Browse to directory holding the copied script file
6.    Run the script:  .\anyfilename.ps1 (assuming anyfilename is the name of the file)

Script is below:

<# ==============================================================
// Microsoft provides programming examples for illustration only,
// without warranty either expressed or implied, including, but not
// limited to, the implied warranties of merchantability and/or
// fitness for a particular purpose.
//
// This sample assumes that you are familiar with the programming
// language being demonstrated and the tools used to create and debug
// procedures. Microsoft support professionals can help explain the
// functionality of a particular procedure, but they will not modify
// these examples to provide added functionality or construct
// procedures to meet your specific needs.

// Author: Russ Maxwell (russmax@microsoft.com)
// ———————————————————-  #>

[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Start-SPAssignment -Global

$starttime = Get-Date
#Creating new site object
$siteurl = Read-Host "Enter the name of your site and press enter"
$site = New-Object Microsoft.SharePoint.SPSite($siteurl)

#Assigning all webs (sites) to $webs
$webs = $site.Allwebs

####################################################
#System Libraries defined so they won’t be touched##
####################################################

$systemlibs =@("Converted Forms", "Customized Reports", "Documents", "Form Templates", 
                              "Images", "List Template Gallery", "Master Page Gallery", "Pages", 
                               "Reporting Templates", "Site Assets", "Site Collection Documents",
                               "Site Collection Images", "Site Pages", "Solution Gallery", 
                               "Style Library", "Theme Gallery", "Web Part Gallery", "wfpub")

Write-Host  "Total number of webs that will be traversed: " $webs.count

$DocLibsCount = 0
$DocLibwItems = 0
$totalitems = 0
$subfolderitems = 0

foreach($web in $webs)
    {
        $listcoll = $web.lists
       
        foreach($list in $listcoll)
        {
             if($list -eq $null)
             {
                Write-Host
             }
             else
             {
                $base = $list.GetType()
                if($base.name -eq "SPDocumentLibrary")
                {
                    if ($systemlibs -contains $list)
                    { continue}
                    else
                        { 
                          $DocLibsCount += 1   
                          $items = $list.items
                         
                          if($items -ne "0")
                          {
                           $DocLibwItems += 1
                           Write-Host "Processing ItemCount for DobLib " $DocLibsCount -ForegroundColor Red
                           $totalitems  += $items.count
                  
                           $name = $list.Title
                           $folders  = $web.GetFolder($name).SubFolders
                           for($etr = 0;$etr -lt $folders.count; $etr++)
                            {
                             if($folders[$etr].Name -ne "Forms")
                               {
                                 Write-Host "Processing SubFolder ItemCount" -ForegroundColor Red
                                 $tempcount = $folders[$etr].ItemCount
                                 $subfolderitems += $tempcount
                                 }
                            }
                           }
                          }
                   }
                 }
              }
          } 
 
Write-Host
Write-Host
Write-Host "Total # of Document Libraries: " $DocLibsCount -ForegroundColor Green
Write-Host "Total # of Document Libraries that contain items: " $DocLibwItems -ForegroundColor Green
Write-Host "Total # of items: " $totalitems -ForegroundColor Green
Write-Host "Total # of items in DocLib\Subfolders: " $subfolderitems -ForegroundColor Green
$finishtime = Get-Date
Write-Host
Write-Host “Script Duration” –ForegroundColor Yellow
Write-Host “Started:   “ $starttime –ForegroundColor Yellow
Write-Host “Finished: “ $finishtime –ForegroundColor Yellow

Stop-SPAssignment -Global

 

Thanks,

Russ Maxwell, MSFT   School bus


Comments (10)

  1. Ilya Oussov says:

    Thank you for the script.

    I suggest to define system libraries as an array, not a pile of scalars, and instead of having long switch with all of them I would test like "if ($syslibs -contains $list) {continue}"

  2. Russ Maxwell says:

    Thanks for the response and great idea.  Let me fine tune it and I'll update it within a couple of days.

  3. Russ Maxwell says:

    Script is updated…  Thx

  4. Luke says:

    Error when running ->  System.Reflection.TargetInvocationException

    Any ideas?

  5. Ella Visani says:

    This is a great script and does nearly what I need. Is there a way to refine it so that I can get a breakdown of how many document per document library? I have a site collection of over 18,000 sites and for a report, I need to produce, I need the number of documents in each site in the collection.

    Let me know if you can help me with this

    Thanks

    Ella

  6. Help sought getting the script to work says:

    So, for 2 of my site collections, the script you provided worked like a champ. However, as I tried the rest of my site collections, I got the error:

    PS C:Userssa_spinstallerDocumentswindows powershell> ./countdocs2.ps1

    Enter the name of your site and press enter: http://myfarm/sites/FacilitiesOperations

    Total number of webs that will be traversed:

    C:Userssa_spinstallerDocumentswindows powershellcountdocs2.ps1 : Exception has been thrown by the target

    of an invocation.

    At line:1 char:17

    + ./countdocs2.ps1 <<<<

       + CategoryInfo          : NotSpecified: (:) [countdocs2.ps1], TargetInvocationException

       + FullyQualifiedErrorId : System.Reflection.TargetInvocationException,countdocs2.ps1

    The weird thing about this is that it says at line 1 – but it already got past that point down to the prompting for the host

    I am using a farm admin account to run this, one that has permissions to the databases, and as I said, it worked for two of the site collections.

    How can I get more detail from the script about the problem it is trying to report?

  7. Larry W. Virden says:

    so, when I log into my server as the sa_farm account, rather than "run as" sa_farm, the script appears to be running better.

    I do have a question about the totals. Does the total # of items include the total number of items in subfolders, or do I need to add those 2 totals together?

    Thank you!

  8. Karim El Zarka says:

    amazing 🙂

  9. John Hudson says:

    Will this work on SharePoint Online?