Get Database File Percentage Free Space via Powershell

Quick post to get the space left in a database file expressed as a percentage, in case you limit the size of your database files in sql server.  I’m not a fan of limiting database file sizes, expressly because most monitoring tools don’t check it (most dbas’ don’t check it either).  Most places I’ve been leave this unlimited and check the drive space (which most monitoring tools do check for).  There’s an argument to be made for each side, but I reside firmly on the unlimited side of the fence.  This happened to me twice yesterday, which only strengthens my argument.  This uses SQLPSX.

	[string]$serverInstance = 'YourServerInstanceName'

Import-Module SqlServer

$outputs = @();

Get-SqlDatabase -sqlserver $serverInstance | %{
	$db = $_
	Get-SqlDataFile -database $_ | %{
		$output = New-Object -TypeName PSObject -Property @{
			DatabaseName = $db.Name
			FileLogicalName = $_.Name
			FileLocation = $_.FileName
			FileGrowthKB = $_.Growth
			MaxSizeKB = $_.MaxSize
			PercentFreeSpace = [Math]::Truncate(($_.AvailableSpace / $_.Size) * 100)
		$outputs += $output	
$outputs | SELECT DatabaseName, FileLogicalName, FileLocation, PercentFreeSpace, FileGrowthKB, MaxSizeKB

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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.