functions/Find-DbaDbUnusedIndex.ps1

function Find-DbaDbUnusedIndex {
    <#
    .SYNOPSIS
        Find unused indexes
 
    .DESCRIPTION
        This command will help you to find Unused indexes on a database or a list of databases
 
        For now only supported for CLUSTERED and NONCLUSTERED indexes
 
    .PARAMETER SqlInstance
        The SQL Server you want to check for unused indexes.
 
    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
    .PARAMETER Database
        The database(s) to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.
 
    .PARAMETER ExcludeDatabase
        Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server.
 
    .PARAMETER IgnoreUptime
        Less than 7 days uptime can mean that analysis of unused indexes is unreliable, and normally no results will be returned. By setting this option results will be returned even if the Instance has been running for less that 7 days.
 
    .PARAMETER InputObject
        Enables piping from Get-DbaDatabase
 
    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
 
    .NOTES
        Tags: Index
        Author: Aaron Nelson (@SQLvariant), SQLvariant.com
 
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
 
    .LINK
        https://dbatools.io/Find-DbaDbUnusedIndex
 
    .EXAMPLE
        PS C:\> Find-DbaDbUnusedIndex -SqlInstance sql2016 -Database db1, db2
 
        Finds unused indexes on db1 and db2 on sql2016
 
    .EXAMPLE
        PS C:\> Find-DbaDbUnusedIndex -SqlInstance sql2016 -SqlCredential $cred
 
        Finds unused indexes on db1 and db2 on sql2016 using SQL Authentication to connect to the server
 
    .EXAMPLE
        PS C:\> Get-DbaDatabase -SqlInstance sql2016 | Find-DbaDbUnusedIndex
 
        Finds unused indexes on all databases on sql2016
 
    #>

    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [switch]$IgnoreUptime,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        # Support Compression 2008+
        $sql = "SELECT SERVERPROPERTY('MachineName') AS ComputerName,
        ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
        SERVERPROPERTY('ServerName') AS SqlInstance, DB_NAME(database_id) AS 'Database'
        ,s.name AS 'Schema'
        ,t.name AS 'Table'
        ,i.object_id AS ObjectId
        ,i.name AS 'IndexName'
        ,i.index_id as 'IndexId'
        ,i.type_desc as 'TypeDesc'
        ,user_seeks as 'UserSeeks'
        ,user_scans as 'UserScans'
        ,user_lookups as 'UserLookups'
        ,user_updates as 'UserUpdates'
        ,last_user_seek as 'LastUserSeek'
        ,last_user_scan as 'LastUserScan'
        ,last_user_lookup as 'LastUserLookup'
        ,last_user_update as 'LastUserUpdate'
        ,system_seeks as 'SystemSeeks'
        ,system_scans as 'SystemScans'
        ,system_lookups as 'SystemLookup'
        ,system_updates as 'SystemUpdates'
        ,last_system_seek as 'LastSystemSeek'
        ,last_system_scan as 'LastSystemScan'
        ,last_system_lookup as 'LastSystemLookup'
        ,last_system_update as 'LastSystemUpdate'
        FROM sys.tables t
        JOIN sys.schemas s
            ON t.schema_id = s.schema_id
        JOIN sys.indexes i
            ON i.object_id = t.object_id LEFT OUTER
        JOIN sys.dm_db_index_usage_stats iu
            ON iu.object_id = i.object_id
                AND iu.index_id = i.index_id
        WHERE iu.database_id = DB_ID()
                AND OBJECTPROPERTY(i.[object_id], 'IsMSShipped') = 0
                AND user_seeks = 0
                AND user_scans = 0
                AND user_lookups = 0
                AND i.type_desc NOT IN ('HEAP', 'CLUSTERED COLUMNSTORE')"

    }

    process {
        if ($SqlInstance) {
            $InputObject += Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
        }

        foreach ($db in $InputObject) {
            if ($db.Parent.Databases[$db].IsAccessible -eq $false) {
                Write-Message -Level Warning -Message "Database [$db] is not accessible."
                continue
            }

            $server = $db.Parent
            $instance = $server.Name

            if ($server.VersionMajor -lt 9) {
                Stop-Function -Message "This function does not support versions lower than SQL Server 2005 (v9)." -Continue
            }

            $lastRestart = $server.Databases['tempdb'].CreateDate
            $endDate = Get-Date -Date $lastRestart
            $diffDays = (New-TimeSpan -Start $endDate -End (Get-Date)).Days

            if ($diffDays -le 6) {
                if ($IgnoreUptime) {
                    Write-Message -Level Verbose -Message "The SQL Service was restarted on $lastRestart, which is not long enough for a solid evaluation."
                } else {
                    Stop-Function -Message "The SQL Service on $instance was restarted on $lastRestart, which is not long enough for a solid evaluation." -Continue
                }
            }

            <#
                Validate if server version is:
                    - sql 2012 and if have SP3 CU3 (Build 6537) or higher
                    - sql 2014 and if have SP2 (Build 5000) or higher
                If the major version is the same but the build is lower, throws the message
            #>


            if (($server.VersionMajor -eq 11 -and $server.BuildNumber -lt 6537) -or ($server.VersionMajor -eq 12 -and $server.BuildNumber -lt 5000)) {
                Stop-Function -Message "This SQL version has a known issue. Rebuilding an index clears any existing row entry from sys.dm_db_index_usage_stats for that index.`r`nPlease refer to connect item: https://support.microsoft.com/en-us/help/3160407/fix-sys-dm-db-index-usage-stats-missing-information-after-index-rebuil" -Continue
            }

            if ($diffDays -le 33) {
                Write-Message -Level Verbose -Message "The SQL Service on $instance was restarted on $lastRestart, which may not be long enough for a solid evaluation."
            }

            try {
                $db.Query($sql)
            } catch {
                Stop-Function -Message "Issue gathering indexes" -Category InvalidOperation -ErrorRecord $_ -Target $db
            }
        }
    }
}