functions/Copy-DbaCentralManagementServer.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
function Copy-DbaCentralManagementServer {
    <#
  .SYNOPSIS
   Migrates SQL Server Central Management groups and server instances from one SQL Server to another.
 
  .DESCRIPTION
   Copy-DbaCentralManagementServer copies all groups, subgroups, and server instances from one SQL Server to another.
 
  .PARAMETER Source
   Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher.
 
  .PARAMETER SourceSqlCredential
   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 -SourceSqlCredential parameter.
 
   Windows Authentication will be used if SourceSqlCredential 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 Destination
   Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher.
 
  .PARAMETER DestinationSqlCredential
   Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use:
 
   $dcred = Get-Credential, then pass this $dcred to the -DestinationSqlCredential parameter.
 
   Windows Authentication will be used if DestinationSqlCredential 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 CMSGroup
   This is an auto-populated array that contains your Central Management Server top-level groups on Source. You can specify one, many or none.
    
   If CMSGroup is not specified, all groups in your Central Management Server will be copied.
    
  .PARAMETER SwitchServerName
   If this switch is enabled, all instance names will be changed from Source to Destination.
    
   Central Management Server does not allow you to add a shared registered server with the same name as the Configuration Server.
 
  .PARAMETER Force
   If this switch is enabled, group(s) will be dropped and recreated if they already exist on Destination.
 
  .PARAMETER WhatIf
   If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
 
  .PARAMETER Confirm
   If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
 
  .PARAMETER Silent
   If this switch is enabled, the internal messaging functions will be silenced.
    
  .NOTES
   Tags: Migration
   Author: Chrissy LeMaire (@cl), netnerds.net
   Requires: sysadmin access on SQL Servers
 
   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/Copy-DbaCentralManagementServer
 
  .EXAMPLE
   Copy-DbaCentralManagementServer -Source sqlserver2014a -Destination sqlcluster
 
   All groups, subgroups, and server instances are copied from sqlserver's Central Management Server to sqlcluster's Central Management Server.
 
  .EXAMPLE
   Copy-DbaCentralManagementServer -Source sqlserver2014a -Destination sqlcluster -ServerGroup Group1,Group3
 
   Top-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster.
 
  .EXAMPLE
   Copy-DbaCentralManagementServer -Source sqlserver2014a -Destination sqlcluster -ServerGroup Group1,Group3 -SwitchServerName -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential $DestinationSqlCredential
 
   Top-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster. When adding sql instances to sqlcluster, if the server name of the migrating instance is "sqlcluster", it will be switched to "sqlserver".
    
   If SwitchServerName is not specified, "sqlcluster" will be skipped.
 #>

    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $true)]
    Param (
        [parameter(Mandatory = $true)]
        [DbaInstanceParameter]$Source,
        [PSCredential]
        $SourceSqlCredential,
        [parameter(Mandatory = $true)]
        [DbaInstanceParameter]$Destination,
        [PSCredential]
        $DestinationSqlCredential,
        [object[]]$CMSGroup,
        [switch]$SwitchServerName,
        [switch]$Force,
        [switch]$Silent
    )
    begin {
        function Invoke-ParseServerGroup {
            [cmdletbinding()]
            param (
                $sourceGroup,
                $destinationGroup,
                $SwitchServerName
            )
            if ($destinationGroup.Name -eq "DatabaseEngineServerGroup" -and $sourceGroup.Name -ne "DatabaseEngineServerGroup") {
                $currentServerGroup = $destinationGroup
                $groupName = $sourceGroup.Name
                $destinationGroup = $destinationGroup.ServerGroups[$groupName]

                $copyDestinationGroupStatus = [pscustomobject]@{
                    SourceServer        = $sourceServer.Name
                    DestinationServer   = $destServer.Name
                    Name                = $groupName
                    Type                = "Create Destination Group"
                    Status              = $null
                    DateTime            = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($null -ne $destinationGroup) {
                    if ($force -eq $false) {
                        $copyDestinationGroupStatus.Status = "Skipped"
                        $copyDestinationGroupStatus
                        Write-Message -Level Warning -Message "Destination group $groupName exists at destination. Use -Force to drop and migrate."
                        continue
                    }
                    if ($Pscmdlet.ShouldProcess($destination, "Dropping group $groupName")) {
                        try {
                            Write-Message -Level Verbose -Message "Dropping group $groupName"
                            $destinationGroup.Drop()
                        }
                        catch {
                            $copyDestinationGroupStatus.Status = "Failed"
                            $copyDestinationGroupStatus

                            Stop-Function -Message "Issue dropping group" -Target $groupName -InnerErrorRecord $_ -Continue
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destination, "Creating group $groupName")) {
                    Write-Message -Level Verbose -Message "Creating group $($sourceGroup.Name)"
                    $destinationGroup = New-Object Microsoft.SqlServer.Management.RegisteredServers.ServerGroup($currentServerGroup, $sourceGroup.Name)
                    $destinationGroup.Create()

                    $copyDestinationGroupStatus.Status = "Successful"
                    $copyDestinationGroupStatus
                }
            }

            # Add Servers
            foreach ($instance in $sourceGroup.RegisteredServers) {
                $instanceName = $instance.Name
                $serverName = $instance.ServerName

                $copyInstanceStatus = [pscustomobject]@{
                    SourceServer        = $sourceServer.Name
                    DestinationServer   = $destServer.Name
                    Name                = $instanceName
                    Type                = "Add Instance"
                    Status              = $null
                    DateTime            = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($serverName.ToLower() -eq $toCmStore.DomainInstanceName.ToLower()) {
                    if ($SwitchServerName) {
                        $serverName = $fromCmStore.DomainInstanceName
                        $instanceName = $fromCmStore.DomainInstanceName
                        Write-Message -Level Verbose -Message "SwitchServerName was used and new CMS equals current server name. $($toCmStore.DomainInstanceName.ToLower()) changed to $serverName."
                    }
                    else {
                        $copyInstanceStatus.Status = "Skipped"
                        $copyInstanceStatus

                        Write-Message -Level Warning -Message "$serverName is Central Management Server. Add prohibited. Skipping."
                        continue
                    }
                }

                if ($destinationGroup.RegisteredServers.Name -contains $instanceName) {
                    if ($force -eq $false) {
                        $copyInstanceStatus.Status = "Skipped"
                        $copyInstanceStatus

                        Write-Message -Level Warning -Message "Instance $instanceName exists in group $groupName at destination. Use -Force to drop and migrate."
                        continue
                    }

                    if ($Pscmdlet.ShouldProcess($destination, "Dropping instance $instanceName from $groupName and recreating")) {
                        try {
                            Write-Message -Level Verbose -Message "Dropping instance $instance from $groupName"
                            $destinationGroup.RegisteredServers[$instanceName].Drop()
                        }
                        catch {
                            $copyInstanceStatus.Status = "Failed"
                            $copyInstanceStatus

                            Stop-Function -Message "Issue dropping instance from group" -Target $instanceName -InnerErrorRecord $_ -Continue
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destination, "Copying $instanceName")) {
                    $newServer = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer($destinationGroup, $instanceName)
                    $newServer.ServerName = $serverName
                    $newServer.Description = $instance.Description

                    if ($serverName -ne $fromCmStore.DomainInstanceName) {
                        $newServer.SecureConnectionString = $instance.SecureConnectionString.ToString()
                        $newServer.ConnectionString = $instance.ConnectionString.ToString()
                    }

                    try {
                        $newServer.Create()

                        $copyInstanceStatus.Status = "Successful"
                        $copyInstanceStatus
                    }
                    catch {
                        $copyInstanceStatus.Status = "Failed"
                        $copyInstanceStatus
                        if ($_.Exception -match "same name") {
                            Stop-Function -Message "Could not add Switched Server instance name." -Target $instanceName -InnerErrorRecord $_ -Continue
                        }
                        else {
                            Stop-Function -Message "Failed to add $serverName" -Target $instanceName -InnerErrorRecord $_ -Continue
                        }
                    }
                    Write-Message -Level Verbose -Message "Added Server $serverName as $instanceName to $($destinationGroup.Name)"
                }
            }

            # Add Groups
            foreach ($fromSubGroup in $sourceGroup.ServerGroups) {
                $fromSubGroupName = $fromSubGroup.Name
                $toSubGroup = $destinationGroup.ServerGroups[$fromSubGroupName]

                $copyGroupStatus = [pscustomobject]@{
                    SourceServer      = $sourceServer.Name
                    DestinationServer = $destServer.Name
                    Name              = $fromSubGroupName
                    Type              = "Add Group"
                    Status            = $null
                    DateTime          = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
                }

                if ($null -ne $toSubGroup) {
                    if ($force -eq $false) {
                        $copyGroupStatus.Status = "Skipped"
                        $copyGroupStatus

                        Write-Message -Level Warning -Message "Subgroup $fromSubGroupName exists at destination. Use -Force to drop and migrate."
                        continue
                    }

                    if ($Pscmdlet.ShouldProcess($destination, "Dropping subgroup $fromSubGroupName recreating")) {
                        try {
                            Write-Message -Level Verbose -Message "Dropping subgroup $fromSubGroupName"
                            $toSubGroup.Drop()
                        }
                        catch {
                            $copyGroupStatus.Status = "Failed"
                            $copyGroupStatus

                            Stop-Function -Message "Issue dropping subgroup" -Target $toSubGroup -InnerErrorRecord $_ -Continue
                        }
                    }
                }

                if ($Pscmdlet.ShouldProcess($destination, "Creating group $($fromSubGroup.Name)")) {
                    Write-Message -Level Verbose -Message "Creating group $($fromSubGroup.Name)"
                    $toSubGroup = New-Object Microsoft.SqlServer.Management.RegisteredServers.ServerGroup($destinationGroup, $fromSubGroup.Name)
                    $toSubGroup.create()

                    $copyGroupStatus.Status = "Successful"
                    $copyGroupStatus
                }

                Invoke-ParseServerGroup -sourceGroup $fromSubGroup -destinationgroup $toSubGroup -SwitchServerName $SwitchServerName
            }
        }

        $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        $destServer = Connect-SqlInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential

        $source = $sourceServer.DomainInstanceName
        $destination = $destServer.DomainInstanceName

        if ($sourceServer.VersionMajor -lt 10 -or $destServer.VersionMajor -lt 10) {
            throw "Central Management Server is only supported in SQL Server 2008 and newer. Quitting."
        }
    }

    process {
        Write-Message -Level Verbose -Message "Connecting to Central Management Servers"

        try {
            $fromCmStore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($sourceServer.ConnectionContext.SqlConnectionObject)
            $toCmStore = New-Object Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore($destServer.ConnectionContext.SqlConnectionObject)
        }
        catch {
            throw "Cannot access Central Management Servers"
        }

        $stores = $fromCmStore.DatabaseEngineServerGroup
        if ($CMSGroup) {
            $stores = @();
            foreach ($groupName in $CMSGroup) {
                $stores += $fromCmStore.DatabaseEngineServerGroup.ServerGroups[$groupName]
            }
        }

        foreach ($store in $stores) {
            Invoke-ParseServerGroup -sourceGroup $store -destinationgroup $toCmStore.DatabaseEngineServerGroup -SwitchServerName $SwitchServerName
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Silent:$false -Alias Copy-SqlCentralManagementServer
    }
}