functions/Get-DbaRestoreHistory.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
function Get-DbaRestoreHistory {
    <#
  .SYNOPSIS
   Returns restore history details for databases on a SQL Server.
    
  .DESCRIPTION
   By default, this command will return the server name, database, username, restore type, date, from file and to files.
 
   Thanks to https://www.mssqltips.com/SqlInstancetip/1724/when-was-the-last-time-your-sql-server-database-was-restored/ for the query and https://sqlstudies.com/2016/07/27/when-was-this-database-restored/ for the idea.
    
  .PARAMETER SqlInstance
   Specifies the SQL Server instance(s) to operate on. Requires SQL Server 2005 or higher.
    
  .PARAMETER SqlCredential
   Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:
 
   $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.
 
   Windows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials.
 
   To connect as a different Windows user, run PowerShell as that user.
 
  .PARAMETER Database
   Specifies 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 Since
   Specifies a datetime to use as the starting point for searching backup history.
    
  .PARAMETER Force
   Deprecated.
 
  .PARAMETER Last
   If this switch is enabled, the last restore action performed on each database is returned.
 
  .NOTES
   Tags: DisasterRecovery, Backup, Restore, Databases
 
   Website: https://dbatools.io
   Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
   License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 
  .LINK
   https://dbatools.io/Get-DbaRestoreHistory
 
  .EXAMPLE
   Get-DbaRestoreHistory -SqlInstance sql2016
 
   Returns server name, database, username, restore type, date for all restored databases on sql2016.
 
  .EXAMPLE
   Get-DbaRestoreHistory -SqlInstance sql2016 -Database db1, db2 -Since '7/1/2016 10:47:00'
 
   Returns restore information only for databases db1 and db2 on sql2016 since July 1, 2016 at 10:47 AM.
    
  .EXAMPLE
   Get-DbaRestoreHistory -SqlInstance sql2014, sql2016 -Exclude db1
 
   Lots of detailed information for all databases except db1 on sql2014 and sql2016.
 
  .EXAMPLE
   Get-DbaRestoreHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs | Format-Table
 
   Adds From and To file information to output, returns information only for AdventureWorks2014 and pubs, and formats the data as a table.
 
  .EXAMPLE
   Get-DbaRegisteredServer -SqlInstance sql2016 | Get-DbaRestoreHistory
 
   Returns database restore information for every database on every server listed in the Central Management Server on sql2016.
   
 #>

    [CmdletBinding()]
    Param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [datetime]$Since,
        [switch]$Force,
        [switch]$Last
    )
    
    begin {
        Test-DbaDeprecation -DeprecatedOn "1.0.0.0" -Silent:$false -Parameter 'Force'

        if ($Since -ne $null) {
            $Since = $Since.ToString("yyyy-MM-dd HH:mm:ss")
        }
    }
    
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
                
                if ($server.VersionMajor -lt 9) {
                    Write-Warning "SQL Server 2000 not supported."
                    continue
                }
                
                $computername = $server.NetName
                $instancename = $server.ServiceName
                $servername = $server.DomainInstanceName
                
                if ($force -eq $true) {
                    $select = "SELECT '$computername' AS [ComputerName],
     '$instancename' AS [InstanceName],
     '$servername' AS [SqlInstance], * "

                }
                else {
                    $select = "SELECT
     '$computername' AS [ComputerName],
     '$instancename' AS [InstanceName],
     '$servername' AS [SqlInstance],
      rsh.destination_database_name AS [Database],
      --rsh.restore_history_id as RestoreHistoryID,
      rsh.user_name AS [Username],
      CASE
       WHEN rsh.restore_type = 'D' THEN 'Database'
       WHEN rsh.restore_type = 'F' THEN 'File'
       WHEN rsh.restore_type = 'G' THEN 'Filegroup'
       WHEN rsh.restore_type = 'I' THEN 'Differential'
       WHEN rsh.restore_type = 'L' THEN 'Log'
       WHEN rsh.restore_type = 'V' THEN 'Verifyonly'
       WHEN rsh.restore_type = 'R' THEN 'Revert'
       ELSE rsh.restore_type
      END AS [RestoreType],
      rsh.restore_date AS [Date],
      ISNULL(STUFF((SELECT ', ' + bmf.physical_device_name
         FROM msdb.dbo.backupmediafamily bmf
           WHERE bmf.media_set_id = bs.media_set_id
         FOR XML PATH('')), 1, 2, ''), '') AS [From],
      ISNULL(STUFF((SELECT ', ' + rf.destination_phys_name
         FROM msdb.dbo.restorefile rf
           WHERE rsh.restore_history_id = rf.restore_history_id
         FOR XML PATH('')), 1, 2, ''), '') AS [To],
     bs.first_lsn,
     bs.last_lsn,
     bs.checkpoint_lsn,
     bs.database_backup_lsn
      "

                }
                
                $from = " FROM msdb.dbo.restorehistory rsh
     INNER JOIN msdb.dbo.backupset bs ON rsh.backup_set_id = bs.backup_set_id"

                
                if ($ExcludeDatabase -or $Database -or $Since -or $last) {
                    $where = " WHERE "
                }
                
                $wherearray = @()
                
                if ($ExcludeDatabase) {
                    $dblist = $ExcludeDatabase -join "','"
                    $wherearray += " destination_database_name not in ('$dblist')"
                }
                
                if ($Database) {
                    $dblist = $Database -join "','"
                    $wherearray += "destination_database_name in ('$dblist')"
                }
                
                if ($Since -ne $null) {
                    $wherearray += "rsh.restore_date >= '$since'"
                }
                

                if ($last) {
                    $wherearray += "rsh.backup_set_id in
      (select max(backup_set_id) from msdb.dbo.restorehistory
      group by destination_database_name
      )"

                }

                if ($where.length -gt 0) {
                    $wherearray = $wherearray -join " and "
                    $where = "$where $wherearray"
                }
                
                $sql = "$select $from $where"
                
                Write-Debug $sql
                
                $results = $server.ConnectionContext.ExecuteWithResults($sql).Tables.Rows 

                if ($last) {
                    $ga = $results | group-Object database
                    $tmpres = @()    
                    $ga | foreach-Object {
                        $tmpres += $_.Group | Sort-Object -Property RESTORE_DATE -Descending | Select-Object -first 1 
                    }
                    $results = $tmpres
                }
                $results | Select-DefaultView -Exclude first_lsn, last_lsn, checkpoint_lsn, database_backup_lsn, RowError, RowState, Table, ItemArray, HasErrors
            }
            catch {
                Write-Warning $_
                Write-Exception $_
                continue
            }
        }
    }
}