functions/Invoke-DbaAdvancedRestore.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
Function Invoke-DbaAdvancedRestore{
    <#
    .SYNOPSIS
        Allows the restore of modified BackupHistory Objects
        For 90% of users Restore-DbaDatabase should be your point of access to this function. The other 10% use it at their own risk
 
    .DESCRIPTION
        This is the final piece in the Restore-DbaDatabase Stack. Uusally a BackupHistory object will arrive here from Restore-DbaDatabse via the following pipeline:
        Get-DbaBackupInformation | Select-DbaBackupInformation | Format-DbaBackupInformation | Test-DbaBackupInformation | Invoke-DbaAdvancedRestore
 
        We have exposed these functions publically to allow advanced users to perform operations that we don't support, or won't add as they would make things too complex for the majority of our users
 
        For example if you wanted to do some very complex redirection during a migration, then doing the rewrite of destinations may be better done with your own custom scripts rather than via Format-DbaBackupInformation
 
        We would recommend ALWAYS pushing your input through Test-DbaBackupInformation just to make sure that it makes sense to us.
 
    .PARAMETER BackupHistory
        The BackupHistory object to be restored.
        Can be passed in on the pipeline
 
    .PARAMETER SqlInstance
        The SqlInstance to which the backups should be restored
 
    .PARAMETER SqlCredential
        SqlCredential to be used to connect to the target SqlInstance
 
    .PARAMETER OutputScriptOnly
        If set, the restore will not be performed, but the T-SQL scripts to perform it will be returned
 
    .PARAMETER VerifyOnly
        If set, performs a Verify of the backups rather than a full restore
 
    .PARAMETER RestoreTime
        Point in Time to which the database should be restored.
 
        This should be the same value or earlier, as used in the previous pipeline stages
 
    .PARAMETER StandbyDirectory
        A folder path where a standby file should be created to put the recoverd databases in a standby mode
 
    .PARAMETER NoRecovery
        Leave the database in a restoring state so that further restore may be made
 
    .PARAMETER MaxTransferSize
        Parameter to set the unit of transfer. Values must be a multiple by 64kb
     
    .PARAMETER Blocksize
        Specifies the block size to use. Must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb or 64kb
        Can be specified in bytes
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail
     
    .PARAMETER BufferCount
        Number of I/O buffers to use to perform the operation.
        Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail
 
    .PARAMETER Continue
        Indicates that the restore is continuing a restore, so target database must be in Recovering or Standby states
     
    .PARAMETER AzureCredential
        AzureCredential required to connect to blob storage holding the backups
 
    .PARAMETER WithReplace
        Indicated that if the database already exists it should be replaced
     
    .PARAMETER WhatIf
        Shows what would happen if the cmdlet runs. The cmdlet is not run.
 
    .PARAMETER Confirm
        Prompts you for confirmation before running the cmdlet.
 
    .PARAMETER EnableException
        Replaces user friendly yellow warnings with bloody red exceptions of doom!
        Use this if you want the function to throw terminating errors you want to catch.
 
    .EXAMPLE
        $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance
 
        Will restore all the backups in the BackupHistory object according to the transformations it contains
 
    .EXAMPLE
        $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance -OutputScriptOnly
        $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance
 
        First generates just the T-SQL restore scripts so they can be sanity checked, and then if they are good perform the full restore. By reusing the BackupHistory object there is no need to rescan all the backup files again
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "Low")]
    param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Object[]]$BackupHistory,
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [switch]$OutputScriptOnly,
        [switch]$VerifyOnly,
        [datetime]$RestoreTime=(Get-Date).AddDays(2),
        [string]$StandbyDirectory,
        [switch]$NoRecovery,
        [int]$MaxTransferSize,
        [int]$BlockSize,
        [int]$BufferCount,
        [switch]$Continue,
        [PSCredential]$AzureCredential,
        [switch]$WithReplace,
        [switch]$EnableException
    )
    begin{
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }
        catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            return
        }
        $ScriptOnly  = $false
        $InternalHistory = @()
    }
    Process{
        ForEach ($bh in $BackupHistory){
            $InternalHistory += $bh
        }
    }
    end{
        $Databases  = $InternalHistory.Database | select-Object -unique
        ForEach ($Database in $Databases){
            If ($Database -in $Server.databases.name) {
                if (($ScriptOnly -eq $true) -or ($verifyonly -ne $true)) {
                    if ($Pscmdlet.ShouldProcess("Killing processes in $Database on $SqlInstance as it exists and WithReplace specified `n", "Cannot proceed if processes exist, ", "Database Exists and WithReplace specified, need to kill processes to restore")) {
                        try {
                            Write-Message -Level Verbose -Message "Set $Database single_user to kill processes"
                            $null = Stop-DbaProcess -SqlInstance $Server -Database $Database -WarningAction Silentlycontinue
                            $null = $server.Query("Alter database $Database set offline with rollback immediate; alter database $Database set restricted_user; Alter database $Database set online with rollback immediate",'master')
                            $server.ConnectionContext.Connect()
                        }
                        catch {
                            Write-Message -Level Verbose -Message "No processes to kill in $Database"
                        }
                    }
                }
                else {
                    Stop-Function -Message "$Database exists and WithReplace not specified, stopping" -EnableException $EnableException 
                    return
                }
            }
            Write-Message -Message "WithReplace = $Withreplace" -Level Verbose
            $backups = $InternalHistory | Where-Object {$_.Database -eq $Database} | Sort-Object -Property Type, FirstLsn
            ForEach ($backup in $backups){
                $Restore = New-Object Microsoft.SqlServer.Management.Smo.Restore
                if (($backup -ne $backups[-1] -and $StandbyDirectory -eq '') -or $true -eq $NoRecovery){
                    $Restore.NoRecovery = $True
                }elseif ($backup -eq $backups[-1] -and '' -ne $StandbyDirectory) {
                    
                    $Restore.StandbyFile = $StandByDirectory + "\" + $Database + (get-date -Format yyyMMddHHmmss) + ".bak"
                    Write-Message -Level Verbose -Message "Setting standby on last file $($Restore.StandbyFile)"
                }
                else {
                    $Restore.NoRecovery = $False
                }
                if ($restoretime -gt (Get-Date)) {
                    $Restore.ToPointInTime = $null
                }
                else {
                    $Restore.ToPointInTime = $RestoreTime
                }
                $Restore.Database = $database
                $Restore.ReplaceDatabase = $WithReplace
                if ($MaxTransferSize) {
                    $Restore.MaxTransferSize = $MaxTransferSize
                }
                if ($BufferCount) {
                    $Restore.BufferCount = $BufferCount
                }
                if ($BlockSize) {
                    $Restore.Blocksize = $BlockSize
                }
                if ($true -ne $Continue){
                    ForEach ($file in $backup.FileList){
                        $MoveFile = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile
                        $MoveFile.LogicalFileName = $File.LogicalName
                        $MoveFile.PhysicalFileName = $File.PhysicalName
                        $null = $Restore.RelocateFiles.Add($MoveFile)
                    }
                }
                $Action = switch ($backup.Type) {
                    '1' {'Database'}
                    '2' {'Log'}
                    '5' {'Database'}
                    'Transaction Log' {'Log'}
                    Default {'Database'}
                }
                Write-Message -Level Verbose -Message "restore action = $Action"
                $Restore.Action = $Action
                ForEach ($File in $backup.fullname){
                    Write-Message -Message "Adding device $file" -Level verbose
                    $Device = New-Object -TypeName Microsoft.SqlServer.Management.Smo.BackupDeviceItem
                    $Device.Name = $file
                    if ($file -like "http*") {
                        $Device.devicetype = "URL"
                        $Restore.CredentialName = $AzureCredential
                    }
                    else {
                        $Device.devicetype = "File"
                    }
                    $Restore.FileNumber = $backup.Position
                    $Restore.Devices.Add($device)
                }
                Write-Message -Level Verbose -Message "Performing restore action"
                $ConfirmMessage = "`n Restore Database $Database on $SqlInstance `n from files: $RestoreFileNames `n with these file moves: `n $LogicalFileMovesString `n $ConfirmPointInTime `n"
                If ($Pscmdlet.ShouldProcess("$Database on $SqlInstance `n `n", $ConfirmMessage)) {
                    try {
                        $RestoreComplete = $true
                        if ($OutputScriptOnly) {
                            $script = $Restore.Script($server)
                        }
                        elseif ($VerifyOnly) {
                            Write-Progress -id 2 -activity "Verifying $Database backup file on $sqlinstance" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
                            $Verify = $Restore.sqlverify($server)
                            Write-Progress -id 2 -activity "Verifying $Database backup file on $sqlinstance" -status "Complete" -Completed
    
                            if ($verify -eq $true) {
                                return "Verify successful"
                            }
                            else {
                                return "Verify failed"
                            }
                        }
                        else {
                            Write-Progress -id 2 -activity "Restoring $Database to $sqlinstance" -percentcomplete 0 -status ([System.String]::Format("Progress: {0} %", 0))
                            $script = $Restore.Script($Server)
                            $Restore.sqlrestore($Server)
                            Write-Progress -id 2 -activity "Restoring $Database to $sqlinstance" -status "Complete" -Completed
                        }
                    }
                    catch {
                        Write-Message -Level Verbose -Message "Failed, Closing Server connection"
                        $RestoreComplete = $False
                        $ExitError = $_.Exception.InnerException
                        Stop-Function -Message "Failed to restore db $Database, stopping" -ErrorRecord $_
                        return
                    }
                    finally {

                        if ($OutputScriptOnly -eq $false) {
                            [PSCustomObject]@{
                                SqlInstance            = $SqlInstance
                                DatabaseName           = $backup.Database
                                DatabaseOwner          = $server.ConnectionContext.TrueLogin
                                NoRecovery             = $Restore.NoRecovery
                                WithReplace            = $WithReplace
                                RestoreComplete        = $RestoreComplete
                                BackupFilesCount       = $backup.FullName.Count
                                RestoredFilesCount     = $backup.Filelist.PhysicalName.count
                                BackupSizeMB           = if ([bool]($backup.psobject.Properties.Name -contains 'BackupSizeMB')) { ($RestoreFiles | Measure-Object -Property BackupSizeMB -Sum).Sum } else { $null }
                                CompressedBackupSizeMB = if ([bool]($backup.psobject.Properties.Name -contains 'CompressedBackupSizeMb')) { ($RestoreFiles | Measure-Object -Property CompressedBackupSizeMB -Sum).Sum } else { $null }
                                BackupFile             = $backup.FullName -Join ','
                                RestoredFile           = $((Split-Path $backup.FileList.PhysicalName -Leaf) | Sort-Object -Unique) -Join ','
                                RestoredFileFull       = ($backup.Filelist.PhysicalName -Join ',')
                                RestoreDirectory       = ((Split-Path $backup.FileList.PhysicalName) | Sort-Object -Unique) -Join ','
                                BackupSize             = if ([bool]($backup.psobject.Properties.Name -contains 'BackupSize')) { ($RestoreFiles | Measure-Object -Property BackupSize -Sum).Sum } else { $null }
                                CompressedBackupSize   = if ([bool]($backup.psobject.Properties.Name -contains 'CompressedBackupSize')) { ($RestoreFiles | Measure-Object -Property CompressedBackupSize -Sum).Sum } else { $null }
                                Script                 = $script
                                BackupFileRaw          = $RestoreFiles
                                ExitError              = $ExitError
                            } | Select-DefaultView -ExcludeProperty BackupSize, CompressedBackupSize, ExitError, BackupFileRaw, RestoredFileFull 
                        }
                        else {
                            $script
                        }
                        while ($Restore.Devices.count -gt 0) {
                            $device = $Restore.devices[0]
                            $null = $Restore.devices.remove($Device)
                        }
                        Write-Message -Level Verbose -Message "Succeeded, Closing Server connection"
                        $server.ConnectionContext.Disconnect()
                    }
                }
                Write-Progress -id 1 -Activity "Restoring" -Completed
            }
            if ($server.ConnectionContext.exists) {
                $server.ConnectionContext.Disconnect()
            }
            }
        }
    }