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