Monitor Content Database Size with Powershell

Simple question.
How large are the content databases?

To solve this, I created a list in Central Administration, and wrote a quick PowerShell script to update the list with my Content Database size(s).

List Name: Content db Size
List Columns: Title, db name, db size (Type = Single line of text)
View: Show Title, db name, db size

PowerShell Script:

if(-not(Get-PSSnapin | where { $_.Name -eq "Microsoft.SharePoint.PowerShell"}))
{
      Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
$adminwebapp = Get-spwebapplication -includecentraladministration | where {$_.IsAdministrationWebApplication}

$siteUrl = $adminwebapp.Url
$listName = "Content db Size"
$spSite = new-object Microsoft.SharePoint.SPSite($siteurl)
$spWeb = $spSite.OpenWeb()
$spList = $spWeb.Lists[$listName]
foreach ($item in $spList.items) { $deaditem = $splist.GetItemById($item.ID); $deaditem.Delete(); }

$webapps = Get-SPWebApplication
foreach($webapp in $webapps)
{
    $ContentDatabases = $webapp.ContentDatabases
    foreach($ContentDatabase in $ContentDatabases)
    {
    $ContentDatabaseSize = [Math]::Round(($ContentDatabase.disksizerequired/1GB),2)
	$addItem = $spList.Items.Add()
	$addItem["Title"] = $webapp.DisplayName
	$addItem["db name"] = $contentdatabase.name
	$addItem["db size"] = $contentdatabasesize
	$addItem.Update()
    }
}

$spWeb.Dispose()

The script is doing the following actions:
Truncate the Content db Size list.
Looping through all the Web Apps.
Updating the Content db Size list with the Web App name, db name, and size.

Taking this to the next level:
Update the existing list item, opposed to truncating the entire list.
Setup a workflow to email you if a db size is greater than X.

*update*

What if you want to get all the Site Collections in a Content Database?
 

$sites = Get-SPSite -Limit All  -ContentDatabase YourContentDatabaseName

foreach($site in $sites)
{
	$siteSize = [math]::round(($site.usage.storage/1GB),2)
	Write-Host $site.url "--" $siteSize
}

2 thoughts on “Monitor Content Database Size with Powershell

  1. This script gives following error:

    PS C:\Scripts> .\GetDBSize.ps1

    You cannot call a method on a null-valued expression.
    At C:\Scripts\GetDBSize.ps1:27 char:2
    + $addItem = $list.Items.Add()
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Cannot index into a null array.
    At C:\Scripts\GetDBSize.ps1:28 char:2
    + $addItem[“Title”] = $webapp.DisplayName
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

  2. $addItem = $list.Items.Add()
    should be:
    $addItem = $spList.Items.Add()

    Thank you for catching that!

Leave a Reply

Your email address will not be published.