Powershell script to get Size of all Tables in Sql Server

Quick script to get the size of all tables in all user databases in sql server.  This reports the size in MB and truncates the decimal points.  This uses SQLPSX, but could be easily converted to use SMO directly.

cls
Import-Module SqlServer
$outputs = @();
$dbs = Get-SqlDatabase -sqlserver "ServerName" | where{$_.IsSystemObject -ne $true}
foreach($db in $dbs)
{
	foreach($table in $db.Tables)
	{
		$output = New-Object -TypeName PSObject -Property @{
			Database = $db.Name
			Schema = $table.Schema
			Table = $table.Name
			Size = [Math]::Truncate(($table.DataSpaceUsed * 1024) / 1MB)
		}
		$outputs += $output
	}
}

$outputs | Sort Size -Descending  | Format-Table -AutoSize



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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.