functions/Test-DbaDbLogShipStatus.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
285
286
287
288
289
290
291
292
293
function Test-DbaDbLogShipStatus {
<#
    .SYNOPSIS
        Test-DbaDbLogShipStatus returns the status of your log shipping databases
 
    .DESCRIPTION
        Most of the time your log shipping "just works".
        Checking your log shipping status can be done really easy with this function.
 
        Make sure you're connecting to the monitoring instance of your log shipping infrastructure.
 
        The function will return the status for a database. This can be one or more messages in a comma separated list.
        If everything is OK with the database than you should only see the message "All OK".
 
    .PARAMETER SqlInstance
        The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater.
 
    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
    .PARAMETER Database
        Allows you to filter the results to only return the databases you're interested in. This can be one or more values separated by commas.
        This is not a wildcard and should be the exact database name. See examples for more info.
 
    .PARAMETER ExcludeDatabase
        Allows you to filter the results to only return the databases you're not interested in. This can be one or more values separated by commas.
        This is not a wildcard and should be the exact database name.
 
    .PARAMETER Primary
        Allows to filter the results to only return values that apply to the primary instance.
 
    .PARAMETER Secondary
        Allows to filter the results to only return values that apply to the secondary instance.
 
    .PARAMETER Simple
        By default all the information will be returned.
        If this parameter is used you get an overview with the SQL Instance, Database, Instance Type and the status
 
    .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: LogShipping
        Author: Sander Stad (@sqlstad), sqlstad.nl
 
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
 
    .LINK
        https://dbatools.io/Test-DbaDbLogShipStatus
 
    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1
 
        Retrieves the log ship information from sql1 and displays all the information present including the status.
 
    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Database AdventureWorks2014
 
        Retrieves the log ship information for just the database AdventureWorks.
 
    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Primary
 
        Retrieves the log ship information and only returns the information for the databases on the primary instance.
 
    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Secondary
 
        Retrieves the log ship information and only returns the information for the databases on the secondary instance.
 
    .EXAMPLE
        PS C:\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Simple
 
        Retrieves the log ship information and only returns the columns SQL Instance, Database, Instance Type and Status
 
#>

    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string[]]$Database,
        [string[]]$ExcludeDatabase,
        [switch]$Simple,
        [switch]$Primary,
        [switch]$Secondary,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        # Setup the query
        [string[]]$query = "
IF ( OBJECT_ID('tempdb..#logshippingstatus') ) IS NOT NULL
BEGIN
DROP TABLE #logshippingstatus;
END;
 
CREATE TABLE #logshippingstatus
(
    Status BIT ,
    IsPrimary BIT ,
    Server VARCHAR(100) ,
    DatabaseName VARCHAR(100) ,
    TimeSinceLastBackup INT ,
    LastBackupFile VARCHAR(255) ,
    BackupThreshold INT ,
    IsBackupAlertEnabled BIT ,
    TimeSinceLastCopy INT ,
    LastCopiedFile VARCHAR(255) ,
    TimeSinceLastRestore INT ,
    LastRestoredFile VARCHAR(255) ,
    LastRestoredLatency INT ,
    RestoreThreshold INT ,
    IsRestoreAlertEnabled BIT
);
 
INSERT INTO #logshippingstatus
( Status ,
    IsPrimary ,
    Server ,
    DatabaseName ,
    TimeSinceLastBackup ,
    LastBackupFile ,
    BackupThreshold ,
    IsBackupAlertEnabled ,
    TimeSinceLastCopy ,
    LastCopiedFile ,
    TimeSinceLastRestore ,
    LastRestoredFile ,
    LastRestoredLatency ,
    RestoreThreshold ,
    IsRestoreAlertEnabled
)
EXEC master.sys.sp_help_log_shipping_monitor"


        $select = "SELECT * FROM #logshippingstatus"

        if ($Database -or $ExcludeDatabase) {

            if ($database) {
                $where += "DatabaseName IN ('$($Database -join ''',''')')"
            }
            elseif ($ExcludeDatabase) {
                $where += "DatabaseName NOT IN ('$($ExcludeDatabase -join ''',''')')"
            }

            $select = "$select WHERE $where"
        }

        $query += $select
        $query += "DROP TABLE #logshippingstatus"
        $sql = $query -join ";`n"
        Write-Message -level Debug -Message $sql
    }

    process {
        foreach ($instance in $sqlinstance) {
            # Try connecting to the instance
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            if ($server.EngineEdition -match "Express") {
                Write-Message -Level Warning -Message "$instance is Express Edition which does not support Log Shipping"
                continue
            }

            # Check the variables
            if ($Primary -and $Secondary) {
                Stop-Function -Message "Invalid parameter combination. Please enter either -Primary or -Secondary" -Target $instance -Continue
            }

            # Get the log shipped databases
            $results = $server.Query($sql)

            # Check if any rows were returned
            if ($results.Count -lt 1) {
                Stop-Function -Message "No information available about any log shipped databases for $instance. Please check the instance name." -Target $instance -Continue
            }

            # Filter the results
            if ($Primary) {
                $results = $results | Where-Object { $_.IsPrimary -eq $true }
            }

            if ($Secondary) {
                $results = $results | Where-Object { $_.IsPrimary -eq $false }
            }

            # Loop through each of the results
            foreach ($result in $results) {

                # Setup a variable to hold the errors
                $statusDetails = @()

                # Check if there are any results that need to be returned
                if ($result.Status -notin 0, 1) {
                    $statusDetails += "N/A"
                }
                else {
                    # Check the status of the row is true which indicates that something is wrong
                    if ($result.Status) {
                        # Check if the row is part of the primary or secondary instance
                        if ($result.IsPrimary) {
                            # Check the backup
                            if (-not $result.TimeSinceLastBackup) {
                                $statusDetails += "The backup has never been executed."
                            }
                            elseif ($result.TimeSinceLastBackup -ge $result.BackupThreshold) {
                                $statusDetails += "The backup has not been executed in the last $($result.BackupThreshold) minutes"
                            }
                        }
                        elseif (-not $result.IsPrimary) {
                            # Check the restore
                            if ($null -eq $result.TimeSinceLastRestore) {
                                $statusDetails += "The restore has never been executed."
                            }
                            elseif ($result.TimeSinceLastRestore -ge $result.RestoreThreshold) {
                                $statusDetails += "The restore has not been executed in the last $($result.RestoreThreshold) minutes"
                            }
                        }
                    }
                    else {
                        $statusDetails += "All OK"
                    }


                    # Check the time for the backup, copy and restore
                    if ($result.TimeSinceLastBackup -eq [DBNull]::Value) {
                        $lastBackup = "N/A"
                    }
                    else {
                        $lastBackup = (Get-Date).AddMinutes(- $result.TimeSinceLastBackup)
                    }

                    if ($result.TimeSinceLastCopy -eq [DBNull]::Value) {
                        $lastCopy = "N/A"
                    }
                    else {
                        $lastCopy = (Get-Date).AddMinutes(- $result.TimeSinceLastCopy)
                    }

                    if ($result.TimeSinceLastRestore -eq [DBNull]::Value) {
                        $lastRestore = "N/A"
                    }
                    else {
                        $lastRestore = (Get-Date).AddMinutes(- $result.TimeSinceLastRestore)
                    }
                }

                # Set up the custom object
                $object = [PSCustomObject]@{
                    ComputerName = $server.ComputerName
                    InstanceName = $server.ServiceName
                    SqlInstance  = $server.DomainInstanceName
                    Database     = $result.DatabaseName
                    InstanceType = switch ($result.IsPrimary) { $true { "Primary Instance" } $false { "Secondary Instance" } }
                    TimeSinceLastBackup = $lastBackup
                    LastBackupFile = $result.LastBackupFile
                    BackupThreshold = $result.BackupThreshold
                    IsBackupAlertEnabled = $result.IsBackupAlertEnabled
                    TimeSinceLastCopy = $lastCopy
                    LastCopiedFile = $result.LastCopiedFile
                    TimeSinceLastRestore = $lastRestore
                    LastRestoredFile = $result.LastRestoredFile
                    LastRestoredLatency = $result.LastRestoredLatency
                    RestoreThreshold = $result.RestoreThreshold
                    IsRestoreAlertEnabled = $result.IsRestoreAlertEnabled
                    Status       = $statusDetails -join ","
                }

                if ($Simple) {
                    $object | Select-DefaultView -Property SqlInstance, Database, InstanceType, Status
                }
                else {
                    $object
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Alias Test-DbaLogShippingStatus
    }
}