functions/Remove-DbaDatabaseMasterKey.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
function Remove-DbaDatabaseMasterKey {
    <#
 .SYNOPSIS
  Deletes specified database master key
  
 .DESCRIPTION
  Deletes specified database master key.
  
 .PARAMETER SqlInstance
  The target SQL Server instance.
  
 .PARAMETER SqlCredential
  Allows you to login to SQL Server using alternative credentials.
  
 .PARAMETER Database
  The database where the master key will be removed.
  
 .PARAMETER ExcludeDatabase
  List of databases to exclude from clearing all master keys
 
 .PARAMETER All
  Purge the master keys from all databases on an instance.
   
 .PARAMETER MasterKeyCollection
  Internal parameter to support pipeline input
  
 .PARAMETER Mode
  Controls how the function handles cases where it can't do anything due to missing database or key:
  Strict: Write a warning (default)
  Lazy: Write a verbose message
  Report: Create a report object as part of the output
  The default action can be adjusted by using Set-DbaConfig to change the 'message.mode.default' configuration
  
 .PARAMETER Silent
  Use this switch to disable any kind of verbose messages
  
 .PARAMETER WhatIf
  Shows what would happen if the command were to run. No actions are actually performed.
  
 .PARAMETER Confirm
  Prompts you for confirmation before executing any changing operations within the command.
  
 .EXAMPLE
  Remove-DbaDatabaseMasterKey -SqlInstance Server1
   
  The master key in the master database on server1 will be removed if it exists.
  
 .EXAMPLE
  Remove-DbaDatabaseMasterKey -SqlInstance Server1 -Database db1 -Confirm:$false
   
  Suppresses all prompts to remove the master key in the 'db1' database and drops the key.
  
  
 .NOTES
  Tags: Certificate
 
  Website: https://dbatools.io
  Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
  License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
#>

    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $true, ConfirmImpact = "High")]
    param (
        [parameter(Mandatory, ParameterSetName = "instanceExplicit")]
        [parameter(Mandatory, ParameterSetName = "instanceAll")]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]
        $SqlInstance,
        
        [System.Management.Automation.PSCredential]
        $SqlCredential,
        
        [parameter(Mandatory, ParameterSetName = "instanceExplicit")]
        [object[]]
        $Database,
        
        [parameter(ParameterSetName = "instanceAll")]
        [object[]]
        $ExcludeDatabase,
        
        [parameter(Mandatory, ParameterSetName = "instanceAll")]
        [switch]
        $All,

        [parameter(ValueFromPipeline, ParameterSetName = "collection")]
        [Microsoft.SqlServer.Management.Smo.MasterKey[]]
        $MasterKeyCollection,
        
        [DbaMode]
        $Mode = (Get-DbaConfigValue -Name 'message.mode.default' -Fallback "Strict"),
        
        [switch]
        $Silent
    )
    
    begin {
        function Drop-Masterkey {
            [CmdletBinding()]
            Param (
                $masterkey,
                
                $mode = $Mode,
                
                $Silent = $Silent
            )
            $server = $masterkey.Parent.Parent
            $instance = $server.DomainInstanceName
            $cert = $masterkey.Name
            $db = $masterkey.Parent
            
            if ($Pscmdlet.ShouldProcess($instance, "Dropping the master key for database '$db'")) {
                try {
                    $masterkey.Drop()
                    Write-Message -Level Verbose -Message "Successfully removed master key from the $db database on $instance"
                    
                    [pscustomobject]@{
                        ComputerName = $server.NetName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.Name
                        Status       = "Success"
                    }
                }
                catch {
                    [pscustomobject]@{
                        ComputerName = $server.NetName
                        InstanceName = $server.ServiceName
                        SqlInstance  = $server.DomainInstanceName
                        Database     = $db.Name
                        Status       = "Failure"
                    }
                    Stop-Function -Message "Failed to drop master key from $db on $instance." -Target $db -InnerErrorRecord $_ -Continue
                }
            }
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                Write-Message -Level Verbose -Message "Connecting to $instance"
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            
            if ($All) {
                $Database = ($server.Databases | Where-Object Name -NotIn $ExcludeDatabase).Name
            }
            
            :Database foreach ($db in $Database) {
                $smodb = $server.Databases[$db]
                $masterkey = $smodb.MasterKey
                
                #region Case: Database Unknown
                if ($null -eq $smodb) {
                    switch ($Mode) {
                        [DbaMode]::Strict { Stop-Function -Message "Database '$db' does not exist on $instance" -Target $smodb -Continue -ContinueLabel database }
                        [DbaMode]::Lazy {
                            Write-Message -Level (Get-DbaConfigValue -Name 'message.mode.lazymessagelevel' -Fallback 4) -Message "Database '$db' does not exist on $instance" -Target $smodb
                            continue database
                        }
                        [DbaMode]::Report {
                            [pscustomobject]@{
                                ComputerName = $server.NetName
                                InstanceName = $server.ServiceName
                                SqlInstance  = $server.DomainInstanceName
                                Database     = $db
                                Status       = "Unknown Database"
                            }
                            continue Database
                        }
                    }
                }
                #endregion Case: Database Unknown
                
                #region Case: No Master Key
                if ($null -eq $masterkey) {
                    switch ($Mode.ToString()) {
                        "Strict" { Stop-Function -Message "No master key exists in the $db database on $instance" -Target $smodb -Continue -ContinueLabel database }
                        "Lazy" {
                            Write-Message -Level (Get-DbaConfigValue -Name 'message.mode.lazymessagelevel' -Fallback 4) -Message "No master key exists in the $db database on $instance" -Target $smodb
                            continue database
                        }
                        "Report" {
                            [pscustomobject]@{
                                ComputerName = $server.NetName
                                InstanceName = $server.ServiceName
                                SqlInstance  = $server.DomainInstanceName
                                Database     = $smodb.Name
                                Status       = "No Masterkey"
                            }
                            continue Database
                        }
                    }
                }
                #endregion Case: No Master Key
                
                Write-Message -Level Verbose -Message "Removing master key from $db"
                Drop-Masterkey -masterkey $masterkey
            }
        }
        
        foreach ($key in $MasterKeyCollection) {
            Write-Message -Level Verbose -Message "Removing master key: $key"
            Drop-Masterkey -masterkey $key
        }
    }
}