Get the item count in a list inside a SharePoint site using PowerShell (Iterate through all subsites)

Here I got my first chance to work with PowerShell and I made it a point to write about this to keep this learning with me.

Requirement – Find the number of items in a list inside a site present in a site collection.

This is as simple as going inside that particular site and check the item count. But the catch was to find item count in 200+ sites present inside a site collection. Now, this isn’t a simple task anymore (lot of manual work, i hate it). Hence, I chose to use PowerShell.

Below is the script that I used. It instantiates the site collection and then iterates through all the sites inside it. Then it looks for the specific list and gets the count. The output for the same is written into an excel file in the defined format.

[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges({ 
 
 $OutputFile = "C:\Users\spdev1glo\Desktop\Powershell"
 $Result = @()
 
 $siteCollectionURL = "http://****/sites/DemoPowershell/"
 $siteColl = Get-SPSite $siteCollectionURL
 
 if($siteColl -ne $null)
{
    foreach($web in $siteColl.AllWebs)
    { 
     if($web -ne $null)
      {
		
		$sourceListName = "TaskList"
		$spSourceList = $web.Lists[$sourceListName]
		$itemCount = $spSourceList.Items.Count
			
		$Result += New-Object PSObject -Property @{
                'List Title' = $spSourceList.Title
                Count = $spSourceList.Items.Count
                'Site Title' = $web.Title
                 URL = $web.URL
			}
	}
    }
   $siteColl.Dispose()    
}

$Result | Select 'Site Title',URL,'List Title',Count | Export-Csv "$OutputFile\SPListReport.csv" -NoTypeInformation

});
Advertisements

One thought on “Get the item count in a list inside a SharePoint site using PowerShell (Iterate through all subsites)

  1. Good article.
    just a note on the adding/removing of the snapin: If you are using the SharePoint PowerShell management shell, its not required to explicitly add/remove the snapins.

    And if you are using the windows powershell, you must also specify the cmdlet for adding the SharePoint snapin at the start of this script so that it recognizes the SharePoint specific classes from the library.

    🙂

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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