functions/Read-DbaBackupHeader.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
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

Function Read-DbaBackupHeader {
<#
.SYNOPSIS
Reads and displays detailed information about a SQL Server backup
 
.DESCRIPTION
Reads full, differential and transaction log backups. An online SQL Server is required to parse the backup files and the path specified must be relative to that SQL Server.
  
.PARAMETER SqlInstance
The SQL Server instance.
 
.PARAMETER SqlCredential
Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.
 
.PARAMETER Path
Path to SQL Server backup file. This can be a full, differential or log backup file.
Accepts valid filesystem paths and URLs
  
.PARAMETER Simple
Returns fewer columns for an easy overview
  
.PARAMETER FileList
Returns detailed information about the files within the backup
 
.PARAMETER AzureCredential
Name of the SQL Server credential that should be used for Azure storage access    
 
.PARAMETER Silent
Switch to silence the internal messaging functions
 
 
.NOTES
Tags: DisasterRecovery, Backup, Restore
dbatools PowerShell module (https://dbatools.io, clemaire@gmail.com)
Copyright (C) 2016 Chrissy LeMaire
 
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
 
.LINK
https://dbatools.io/Read-DbaBackupHeader
 
.EXAMPLE
Read-DbaBackupHeader -SqlInstance sql2016 -Path S:\backups\mydb\mydb.bak
 
Logs into sql2016 using Windows authentication and reads the local file on sql2016, S:\backups\mydb\mydb.bak.
  
If you are running this command on a workstation and connecting remotely, remember that sql2016 cannot access files on your own workstation.
 
.EXAMPLE
Read-DbaBackupHeader -SqlInstance sql2016 -Path \\nas\sql\backups\mydb\mydb.bak, \\nas\sql\backups\otherdb\otherdb.bak
 
Logs into sql2016 and reads two backup files - mydb.bak and otherdb.bak. The SQL Server service account must have rights to read this file.
  
.EXAMPLE
Read-DbaBackupHeader -SqlInstance . -Path C:\temp\myfile.bak -Simple
  
Logs into the local workstation (or computer) and shows simplified output about C:\temp\myfile.bak. The SQL Server service account must have rights to read this file.
 
.EXAMPLE
$backupinfo = Read-DbaBackupHeader -SqlInstance . -Path C:\temp\myfile.bak
$backupinfo.FileList
  
Displays detailed information about each of the datafiles contained in the backupset.
 
.EXAMPLE
Read-DbaBackupHeader -SqlInstance . -Path C:\temp\myfile.bak -FileList
  
Also returns detailed information about each of the datafiles contained in the backupset.
 
.EXAMPLE
"C:\temp\myfile.bak", "\backupserver\backups\myotherfile.bak" | Read-DbaBackupHeader -SqlInstance sql2016
 
Similar to running Read-DbaBackupHeader -SqlInstance sql2016 -Path "C:\temp\myfile.bak", "\backupserver\backups\myotherfile.bak"
  
.EXAMPLE
Get-ChildItem \\nas\sql\*.bak | Read-DbaBackupHeader -SqlInstance sql2016
 
Gets a list of all .bak files on the \\nas\sql share and reads the headers using the server named "sql2016". This means that the server, sql2016, must have read access to the \\nas\sql share.
 
.EXAMPLE
Read-DbaBackupHeader -Path https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak
 -AzureCredential AzureBackupUser
 
Gets the backup header information from the SQL Server backup file stored at https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak on Azure
#>

    [CmdletBinding()]
    Param (
        [parameter(Mandatory = $true)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]
        $SqlInstance,
        
        [PsCredential]
        $SqlCredential,
        
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [object[]]
        $Path,
        
        [switch]
        $Simple,
        
        [switch]
        $FileList,
        
        [string]
        $AzureCredential,
        
        [switch]
        $Silent
    )
    
    begin {
        $LoopCnt = 1
        
        try {
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
        }
        catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            return
        }
    }
    
    process {
        if (Test-FunctionInterrupt) { return }
        $PathCount = $path.length
        Write-Message -Level Verbose -Message "$pathcount files to scan"
        foreach ($file in $path) {
            if ($null -ne $file.FullName) { $file = $file.FullName }
            Write-Progress -Id 1 -Activity Updating -Status 'Progress' -CurrentOperation "Scanning Restore headers on File $LoopCnt - $file"
            
            Write-Message -Level Verbose -Message "Scanning file $file"
            $restore = New-Object Microsoft.SqlServer.Management.Smo.Restore
            if ($file -like 'http*') {
                $DeviceType = 'URL'
                $restore.CredentialName = $AzureCredential
            }
            else {
                $DeviceType = 'FILE'
            }
            $device = New-Object Microsoft.SqlServer.Management.Smo.BackupDeviceItem $file, $DeviceType
            $restore.Devices.Add($device)
            if ((Test-DbaSqlPath -SqlInstance $server -Path $file) -or $DeviceType -eq 'URL') {
                <#    try
     {
      $allfiles = $restore.ReadFileList($server)
     }
     catch
     {
      $shortname = Split-Path $file -Leaf
      if (!(Test-DbaSqlPath -SqlInstance $server -Path $file))
      {
       Write-Warning "File $shortname does not exist or access denied. The SQL Server service account may not have access to the source directory."
      }
      else
      {
       Write-Warning "File list for $shortname could not be determined. This is likely due to the file not existing, the backup version being incompatible or unsupported, connectivity issues or tiemouts with the SQL Server, or the SQL Server service account does not have access to the source directory."
      }
     }
      
 
    }#>

                try {
                    $datatable = $restore.ReadBackupHeader($server)
                }
                catch {
                    Write-Exception $_
                    if ($DeviceType -eq 'FILE') {
                        Write-Message -Level Warning -Message "Problem with $file"
                    }
                    else {
                        Write-Message -Level Warning -Message "Cannot reach $file, check credential name and network connectivity"
                    }
                    Return
                }
                $fl = $datatable.Columns.Add("FileList", [object])
                #$datatable.rows[0].FileList = $allfiles.rows
                
                $mb = $datatable.Columns.Add("BackupSizeMB", [int])
                $mb.Expression = "BackupSize / 1024 / 1024"
                $gb = $datatable.Columns.Add("BackupSizeGB")
                $gb.Expression = "BackupSizeMB / 1024"
                
                if ($null -eq $datatable.Columns['CompressedBackupSize']) {
                    $formula = "0"
                }
                else {
                    $formula = "CompressedBackupSize / 1024 / 1024"
                }
                
                $cmb = $datatable.Columns.Add("CompressedBackupSizeMB", [int])
                $cmb.Expression = $formula
                $cgb = $datatable.Columns.Add("CompressedBackupSizeGB")
                $cgb.Expression = "CompressedBackupSizeMB / 1024"
                
                $null = $datatable.Columns.Add("SqlVersion")
                
                
                $null = $datatable.Columns.Add("BackupPath")
                #    $datatable.Columns["BackupPath"].DefaultValue = $Path
                $dbversion = $datatable.Rows[0].DatabaseVersion
                
                #    $datatable.Rows[0].SqlVersion = (Convert-DbVersionToSqlVersion $dbversion)
                $BackupSlot = 1
                ForEach ($row in $DataTable) {
                    $row.SqlVersion = (Convert-DbVersionToSqlVersion $dbversion)
                    $row.BackupPath = $file
                    try {
                        $restore.FileNumber = $BackupSlot
                        $allfiles = $restore.ReadFileList($server)
                    }
                    catch {
                        $shortname = Split-Path $file -Leaf
                        if (!(Test-DbaSqlPath -SqlInstance $server -Path $file)) {
                            Write-Message -Level Warning -Message "File $shortname does not exist or access denied. The SQL Server service account may not have access to the source directory."
                        }
                        else {
                            Write-Message -Level Warning -Message "File list for $shortname could not be determined. This is likely due to the file not existing, the backup version being incompatible or unsupported, connectivity issues or tiemouts with the SQL Server, or the SQL Server service account does not have access to the source directory."
                        }
                        
                        #Write-Exception $_
                        #return
                    }
                    $row.FileList = $allfiles
                    $BackupSlot++
                    
                }
            }
            else {
                Write-Message -Level Warning -Message "File $shortname does not exist or access denied. The SQL Server service account may not have access to the source directory."
                return
            }
            if ($Simple) {
                $datatable | Select-Object DatabaseName, BackupFinishDate, RecoveryModel, BackupSizeMB, CompressedBackupSizeMB, DatabaseCreationDate, UserName, ServerName, SqlVersion, BackupPath
            }
            elseif ($FileList) {
                $datatable.filelist
            }
            else {
                $datatable
            }
            
            Remove-Variable DataTable -ErrorAction SilentlyContinue
        }
        $LoopCnt++
    }
}