Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions Links


SQL Server DBA Jobs

How to get SQL Server database object count using Powershell Measure-Object

24 July,2019 by Tom Collins

Question: How can I iterate through a list of SQL Servers , extract the count of the databases , place into a powershell data table and get the database count sum for all the servers?

I'm having some trouble thinking about how to add up the counts from the individual servers into a total count , using powershell functions.

Answer: This basic  powershell script will give you the basic framework. 

This script iterates through a list of SQL Servers - listed in the file referenced in the $instancepath. The results of the command executed  are added to the DataTable . Once all the servers are touched and the results are placed in the DataTable .

The last line uses the Measure-Object cmdlet.  This cmdlet calculates the numeric properties of objects, and in this case, using the -Sum parameter will add the count numbers in the DataTable.



$dt = new-object "System.Data.DataTable"
foreach ($instance in get-content $instancepath)
$cn = new-object System.Data.SqlClient.SqlConnection "server=$instance;database=master;Integrated Security=sspi"
$sql = $cn.CreateCommand()
$sql.CommandText = "select count(*) from sys.databases"
$rdr = $sql.ExecuteReader()

$dt | Measure-Object -Sum Column1 | out-host

Read More on Powershell Datatables

How to add a row in Powershell System.Data.Datatable (SQL Server ...



Author: Tom Collins (


Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.


Post a comment on How to get SQL Server database object count using Powershell Measure-Object | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer