Count any type of document in your SharePoint farm using PowerShell

Have you experienced a scenario when you have multiple SharePoint content databases across multiple SQL Servers. The scenario I had was following:

1. 3 SQL Servers.

2. Each SQL Server hosts multiple content databases

I did not want to write a script with the name of all the content databases but my script should pickup any SQL Server content database with the word “contet” in the database name. I save the SQL Server to a local file and call the query from PowerShell. In the script there are 2 variables defined, 1 the queryfile and 2 the SharePoint SQL Server instances. Here I am finding the total number of PDFs in my farm but you can use it to find any type of document. The script is as below (rememeber you need Farm Admin access and also need access to SQL Servers):

Save the script below as DocumentCount.ps1 and remember to save the SQL script to your desired location.

#Script starts here

$spqueryfile = “C:\SPDBQuery.sql” 

$sharepointDBinstances = @(“Server\SQLInstance1”,“Server\SQLInstance2”,“Server3\SQLInstance3”)

 $Final = 0 

foreach($sharepointDBinstance in $sharepointDBinstances){

 $initialresult= Invoke-Sqlcmd -ServerInstance $sharepointinstance -InputFile  $spqueryfile

 if (!$initialresult.HasErrors -eq $true){

 $Qresult = $initialresult | %{$_.Count} 

$Sum = $Qresult -join ‘+’ 

$Totals = Invoke-Expression $Sum

 $output “total PDFs in your SharePoint Farm”

    $Final = $Totals $Final

 }

}

Write-Host “The $output has value $Final”

#End of PowerShell script

The SQL Query is, you can change the query to report of doc or xlsx etc:

–Start of SQL Script

DECLARE @DBNAME VARCHAR(100), @STMT NVARCHAR(MAX)
DECLARE DBNAME_CURSOR CURSOR READ_ONLY
 for select name from sys.databases
   where name like (‘%content%’)
OPEN DBNAME_CURSOR  
FETCH NEXT FROM DBNAME_CURSOR into @DBNAME
WHILE @@FETCH_STATUS = 0
 BEGIN
  SET @STMT = ‘SELECT COUNT(*) as Count FROM ‘ + @dbname + ‘.[dbo].[AllDocs] (NOLOCK) WHERE Extension = ”pdf”’
  EXEC sp_executesql @STMT
 FETCH NEXT FROM DBNAME_CURSOR into @DBNAME
 END
 CLOSE DBNAME_CURSOR
  DEALLOCATE DBNAME_CURSOR

 —End of SQL Script

Hit like if you like what you see…..

Advertisements