Friday, 13 March 2015

Powershell - Index Fragmentation

Import-Module SQLPS -DisableNameChecking

#current server name
$servername = "ROGUE"
$database = "Chinook"

$query = @"
SELECT
  OBJECT_NAME(phys_stats.OBJECT_ID) AS [Object], 
  idx.name AS [Index Name], 
  phys_stats.index_type_desc [Index Type], 
  phys_stats.avg_fragmentation_in_percent [Fragmentation %],
  phys_stats.page_count [# Pages]
FROM
  sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS phys_stats
  INNER JOIN sys.indexes AS idx WITH (NOLOCK)
  ON phys_stats.[object_id] = idx.[object_id]
  AND phys_stats.index_id = idx.index_id
WHERE
  phys_stats.database_id = DB_ID()
ORDER BY
  phys_stats.avg_fragmentation_in_percent DESC;
"@

Invoke-Sqlcmd -ServerInstance $servername -Database $database -Query $query | Format-Table -AutoSize

No comments:

Post a Comment