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.

param(
	[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
Advertisements

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: