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

});