Sharepoint: PowerShell script to find number of documents in Document library in each site and site collection

One of the most discussed topic in any large organisation which is using SharePoint to manage their solutions is ***GOVERNANCE. ***

One of the major problem SharePoint administrators faces is, they don't have much control on content which is being uploaded in SharePoint as any user who is having contribute access or more can upload any number of documents, which in turn increases the content database size.

I have created a PowerShell script to help administrators to know the number of documents in the farm. The flow of the script is as follows:

  1. It goes through each web application and print web app name.
  2. Then it goes to each site collection and print site collection name.
  3. Then it counts number of sites in the site collection.
  4. Then it goes to default 'Documents' document library in each site and provides the document count.
  5. So, finally you would know how many sites are present in a site collection, how many documents is there on a particular site as well as site collection.

The result of the script will be sent to a text file.

[System.Reflection.Assembly]::LoadWithPartialName(?Microsoft.SharePoint?) > $null
try{
   $farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
  $websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
  $stream = [System.IO.StreamWriter] ?E:\Report$(get-date -f yyyy-MM-dd_hh_mm).txt?
   foreach ($websvc in $websvcs) {
    foreach ($webapp in $websvc.WebApplications) {
      $stream.WriteLine(?WebApplication Name ?>? + $webapp.Name)
      foreach ($site in $webapp.Sites) {
        $count = 0
        $stream.WriteLine(?Site Collection Title?> ?>? + $site.RootWeb.Title)
        $stream.WriteLine(?Number of Sites in the SiteCollection ? + $site.RootWeb.Title + ? ?> ?>? + $site.AllWebs.Count)

        if($site.AllWebs.Count -ne 0)
        {
          foreach ($web in $site.AllWebs) {
            foreach ($list in $web.Lists) {
              if($list.Hidden -ne ?True? -and $list.BaseTemplate -eq ?DocumentLibrary?){
                if($list.Title -eq ?Documents?)
                  {
                    $stream.WriteLine(?Site URL ?> ?> ?>? + $web.Url)
                    $stream.WriteLine(?Document Count ?> ?> ?>? + $list.Items.Count)
                    $count = $count + $list.Items.Count
                    }
                 }
              }
           }
         #end of if statement
           }
       $stream.WriteLine(?Total No of documents in ? + $site.URL + ? ?> ?> ? +$count)
        }
      }
    }
  }
  catch [Exception]{
  $stream.WriteLine( $_.Exception.Message)
  }finally{
  $ErrorActionPreference = ?Continue?;
  }
$stream.close()

       

The above script has been tested in multiple environments.