Repository navigation
Expand file tree
/
Copy pathCopy-DbaSystemDbUserObject.ps1
More file actions
425 lines (384 loc) 路 26.1 KB
/
Copy pathCopy-DbaSystemDbUserObject.ps1
File metadata and controls
425 lines (384 loc) 路 26.1 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
function Copy-DbaSystemDbUserObject {
<#
.SYNOPSIS
Copies user-created objects from system databases (master, msdb, model) between SQL Server instances.
.DESCRIPTION
Migrates custom database objects that DBAs commonly store in system databases like maintenance procedures, monitoring tables, custom triggers, and backup utilities from master and msdb. Also transfers objects from the model database that will be included in new databases created on the destination instance.
This function handles schemas, tables, views, stored procedures, functions, triggers, and other user-defined objects while preserving dependencies and permissions. It's particularly valuable during server migrations or when standardizing DBA tooling across multiple instances.
.PARAMETER Source
Specifies the source SQL Server instance containing the user objects to copy from system databases.
Requires sysadmin permissions to access master, msdb, and model databases for object extraction.
.PARAMETER SourceSqlCredential
Specifies credentials for connecting to the source SQL Server instance when Windows Authentication is not available.
Required when accessing source instances across domains or using SQL Server Authentication.
.PARAMETER Destination
Specifies one or more destination SQL Server instances where the user objects will be copied to.
Requires sysadmin permissions to modify master, msdb, and model databases on the destination servers.
.PARAMETER DestinationSqlCredential
Specifies credentials for connecting to destination SQL Server instances when Windows Authentication is not available.
Required when accessing destination instances across domains or using SQL Server Authentication.
.PARAMETER Classic
Uses the legacy migration method that copies all object types in bulk using SQL Server Management Objects Transfer class.
The default modern method provides better error handling and granular object control but this option may resolve compatibility issues with older SQL Server versions.
.PARAMETER Force
Drops existing objects on destination instances before creating new ones to resolve naming conflicts.
Only works with the default modern method, not with Classic mode, and may fail with objects that have dependencies.
.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 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: Migration, SystemDatabase, UserObject
Author: Chrissy LeMaire (@cl), netnerds.net
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.OUTPUTS
PSCustomObject (default when -Classic is not specified)
Returns one object per user-defined object (schema, table, view, function, trigger, etc.) copied from system databases. The Classic mode returns no output.
Properties:
- DateTime: The date and time the operation completed (DbaDateTime)
- SourceServer: The name of the source SQL Server instance
- DestinationServer: The name of the destination SQL Server instance
- Name: The name of the object copied (schema name, table name, or fully qualified object name with schema)
- Type: The type of object and system database (e.g., "User schema in master", "User table in msdb", "User stored procedure in master")
- Status: The result of the copy operation (Successful, Skipped, or Failed)
- Notes: Additional context about the operation result (e.g., "Already exists on destination", "May have also created dependencies", error details)
.LINK
https://dbatools.io/Copy-DbaSystemDbUserObject
.EXAMPLE
PS C:\> Copy-DbaSystemDbUserObject -Source sqlserver2014a -Destination sqlcluster
Copies user objects found in system databases master, msdb and model from sqlserver2014a instance to the sqlcluster instance.
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[DbaInstanceParameter]$Source,
[PSCredential]$SourceSqlCredential,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[DbaInstanceParameter[]]$Destination,
[PSCredential]$DestinationSqlCredential,
[switch]$Force,
[switch]$Classic,
[switch]$EnableException
)
begin {
if ($Force) { $ConfirmPreference = 'none' }
function get-sqltypename ($type) {
switch ($type) {
"VIEW" { "view" }
"SQL_TABLE_VALUED_FUNCTION" { "User table valued function" }
"DEFAULT_CONSTRAINT" { "User default constraint" }
"SQL_STORED_PROCEDURE" { "User stored procedure" }
"RULE" { "User rule" }
"SQL_INLINE_TABLE_VALUED_FUNCTION" { "User inline table valued function" }
"SQL_TRIGGER" { "User server trigger" }
"SQL_SCALAR_FUNCTION" { "User scalar function" }
default { $type }
}
}
}
process {
try {
$sourceServer = Connect-DbaInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
} catch {
Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
return
}
if (!(Test-SqlSa -SqlInstance $sourceServer -SqlCredential $SourceSqlCredential)) {
Stop-Function -Message "Not a sysadmin on $source. Quitting."
return
}
if (Test-FunctionInterrupt) { return }
foreach ($destinstance in $Destination) {
try {
$destServer = Connect-DbaInstance -SqlInstance $destinstance -SqlCredential $DestinationSqlCredential
} catch {
Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $destinstance -Continue
}
if (!(Test-SqlSa -SqlInstance $destServer -SqlCredential $DestinationSqlCredential)) {
Stop-Function -Message "Not a sysadmin on $destinstance" -Continue
}
$systemDbs = "master", "model", "msdb"
if (-not $Classic) {
foreach ($systemDb in $systemDbs) {
$smodb = $sourceServer.databases[$systemDb]
$destdb = $destserver.databases[$systemDb]
$tables = $smodb.Tables | Where-Object IsSystemObject -ne $true
$schemas = $smodb.Schemas | Where-Object IsSystemObject -ne $true
foreach ($schema in $schemas) {
$copyobject = [PSCustomObject]@{
SourceServer = $sourceServer.Name
DestinationServer = $destServer.Name
Name = $schema
Type = "User schema in $systemDb"
Status = $null
Notes = $null
DateTime = [Dataplat.Dbatools.Utility.DbaDateTime](Get-Date)
}
$destschema = $destdb.Schemas | Where-Object Name -eq $schema.Name
if ($destschema) {
if (-not $force) {
if ($PSCmdlet.ShouldProcess($destInstance, "Skipping schema $schema because it already exists on the destination instance. Use -Force to drop and recreate")) {
$copyobject.Status = "Skipped"
$copyobject.Notes = "Already exists on destination"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
}
continue
} else {
if ($PSCmdlet.ShouldProcess($destInstance, "Dropping schema $schema in $systemDb")) {
try {
Write-Message -Level Verbose -Message "Force specified. Dropping $schema in $destdb on $destinstance"
$destschema.Drop()
} catch {
$copyobject.Status = "Failed"
$copyobject.Notes = $_.Exception.InnerException.InnerException.InnerException.Message
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
continue
}
}
}
}
$transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
$null = $transfer.CopyAllObjects = $false
$null = $transfer.Options.WithDependencies = $true
$null = $transfer.Options.ScriptOwner = $true
$null = $transfer.ObjectList.Add($schema)
if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to add schema $($schema.Name) to $systemDb")) {
try {
$sql = $transfer.ScriptTransfer()
Write-Message -Level Debug -Message "$sql"
$null = $destServer.Query($sql, $systemDb)
$copyobject.Status = "Successful"
$copyobject.Notes = "May have also created dependencies"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
} catch {
$copyobject.Status = "Failed"
$copyobject.Notes = (Get-ErrorMessage -Record $_)
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
continue
}
}
}
foreach ($table in $tables) {
$copyobject = [PSCustomObject]@{
SourceServer = $sourceServer.Name
DestinationServer = $destServer.Name
Name = $table
Type = "User table in $systemDb"
Status = $null
Notes = $null
DateTime = [Dataplat.Dbatools.Utility.DbaDateTime](Get-Date)
}
$desttable = $destdb.Tables.Item($table.Name, $table.Schema)
if ($desttable) {
if (-not $force) {
if ($PSCmdlet.ShouldProcess($destInstance, "Skipping table $desttable because it already exists on the destination instance. Use -Force to drop and recreate")) {
$copyobject.Status = "Skipped"
$copyobject.Notes = "Already exists on destination"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
}
continue
} else {
if ($PSCmdlet.ShouldProcess($destInstance, "Dropping table $table in $systemDb")) {
try {
Write-Message -Level Verbose -Message "Force specified. Dropping $table in $destdb on $destinstance"
$desttable.Drop()
} catch {
$copyobject.Status = "Failed"
$copyobject.Notes = $_.Exception.InnerException.InnerException.InnerException.Message
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
continue
}
}
}
}
$transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
$null = $transfer.CopyAllObjects = $false
$null = $transfer.Options.WithDependencies = $true
$null = $transfer.Options.Indexes = $true
if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to add table $table to $systemDb")) {
try {
$null = $transfer.ObjectList.Add($table)
$sql = $transfer.ScriptTransfer()
Write-Message -Level Debug -Message "$sql"
$null = $destServer.Query($sql, $systemDb)
$copyobject.Status = "Successful"
$copyobject.Notes = "May have also created dependencies"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
} catch {
$copyobject.Status = "Failed"
$copyobject.Notes = (Get-ErrorMessage -Record $_)
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
continue
}
}
}
$userobjects = Get-DbaModule -SqlInstance $sourceserver -Database $systemDb -ExcludeSystemObjects | Sort-Object Type
Write-Message -Level Verbose -Message "Copying from $systemDb"
foreach ($userobject in $userobjects) {
$name = "[$($userobject.SchemaName)].[$($userobject.Name)]"
$db = $userobject.Database
$type = get-sqltypename $userobject.Type
$sql = $userobject.Definition
$schema = $userobject.SchemaName
$copyobject = [PSCustomObject]@{
SourceServer = $sourceServer.Name
DestinationServer = $destServer.Name
Name = $name
Type = "$type in $systemDb"
Status = $null
Notes = $null
DateTime = [Dataplat.Dbatools.Utility.DbaDateTime](Get-Date)
}
Write-Message -Level Debug -Message $sql
try {
Write-Message -Level Verbose -Message "Searching for $name in $db on $destinstance"
$result = Get-DbaModule -SqlInstance $destServer -ExcludeSystemObjects -Database $db |
Where-Object { $PSItem.Name -eq $userobject.Name -and $PSItem.Type -eq $userobject.Type }
if ($result) {
Write-Message -Level Verbose -Message "Found $name in $db on $destinstance"
if (-not $Force) {
if ($PSCmdlet.ShouldProcess($destInstance, "Object $name already exists, skipping")) {
$copyobject.Status = "Skipped"
$copyobject.Notes = "Already exists on destination"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
}
continue
} else {
$smobject = switch ($userobject.Type) {
"VIEW" { $smodb.Views.Item($userobject.Name, $userobject.SchemaName) }
"SQL_STORED_PROCEDURE" { $smodb.StoredProcedures.Item($userobject.Name, $userobject.SchemaName) }
"RULE" { $smodb.Rules.Item($userobject.Name, $userobject.SchemaName) }
"SQL_TRIGGER" { $smodb.Triggers.Item($userobject.Name, $userobject.SchemaName) }
"SQL_TABLE_VALUED_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
"SQL_INLINE_TABLE_VALUED_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
"SQL_SCALAR_FUNCTION" { $smodb.UserDefinedFunctions.Item($name) }
}
if ($smobject) {
Write-Message -Level Verbose -Message "Force specified. Dropping $smobject on $destdb on $destinstance using SMO"
$transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
$null = $transfer.CopyAllObjects = $false
$null = $transfer.Options.WithDependencies = $true
$null = $transfer.ObjectList.Add($smobject)
$null = $transfer.Options.ScriptDrops = $true
$dropsql = $transfer.ScriptTransfer()
Write-Message -Level Debug -Message "$dropsql"
if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to drop $type $name from $systemDb")) {
$null = $destdb.Query("$dropsql")
}
} else {
if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to drop $type $name from $systemDb using T-SQL")) {
$null = $destdb.Query("DROP FUNCTION $($userobject.name)")
}
}
if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to add $type $name to $systemDb")) {
$null = $destdb.Query("$sql")
$copyobject.Status = "Successful"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
}
}
} else {
if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to add $type $name to $systemDb")) {
$null = $destdb.Query("$sql")
$copyobject.Status = "Successful"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
}
}
} catch {
try {
$smobject = switch ($userobject.Type) {
"VIEW" { $smodb.Views.Item($userobject.Name, $userobject.SchemaName) }
"SQL_STORED_PROCEDURE" { $smodb.StoredProcedures.Item($userobject.Name, $userobject.SchemaName) }
"RULE" { $smodb.Rules.Item($userobject.Name, $userobject.SchemaName) }
"SQL_TRIGGER" { $smodb.Triggers.Item($userobject.Name, $userobject.SchemaName) }
}
if ($smobject) {
$transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb
$null = $transfer.CopyAllObjects = $false
$null = $transfer.Options.WithDependencies = $true
$null = $transfer.ObjectList.Add($smobject)
$sql = $transfer.ScriptTransfer()
Write-Message -Level Debug -Message "$sql"
Write-Message -Level Verbose -Message "Adding $smoobject on $destdb on $destinstance"
if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to add $type $name to $systemDb")) {
$null = $destdb.Query("$sql")
}
$copyobject.Status = "Successful"
$copyobject.Notes = "May have also installed dependencies"
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
} else {
$copyobject.Status = "Failed"
$copyobject.Notes = (Get-ErrorMessage -Record $_)
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
continue
}
} catch {
$copyobject.Status = "Failed"
$copyobject.Notes = (Get-ErrorMessage -Record $_)
$copyobject | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject
continue
}
}
}
}
} else {
foreach ($systemDb in $systemDbs) {
$sysdb = $sourceServer.databases[$systemDb]
$transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $sysdb
$transfer.CopyAllObjects = $false
$transfer.CopyAllDatabaseTriggers = $true
$transfer.CopyAllDefaults = $true
$transfer.CopyAllRoles = $true
$transfer.CopyAllRules = $true
$transfer.CopyAllSchemas = $true
$transfer.CopyAllSequences = $true
$transfer.CopyAllSqlAssemblies = $true
$transfer.CopyAllSynonyms = $true
$transfer.CopyAllTables = $true
$transfer.CopyAllViews = $true
$transfer.CopyAllStoredProcedures = $true
$transfer.CopyAllUserDefinedAggregates = $true
$transfer.CopyAllUserDefinedDataTypes = $true
$transfer.CopyAllUserDefinedTableTypes = $true
$transfer.CopyAllUserDefinedTypes = $true
$transfer.CopyAllUserDefinedFunctions = $true
$transfer.CopyAllUsers = $true
$transfer.PreserveDbo = $true
$transfer.Options.AllowSystemObjects = $false
$transfer.Options.ContinueScriptingOnError = $true
$transfer.Options.IncludeDatabaseRoleMemberships = $true
$transfer.Options.Indexes = $true
$transfer.Options.Permissions = $true
$transfer.Options.WithDependencies = $false
Write-Message -Level Output -Message "Copying from $systemDb."
try {
$sqlQueries = $transfer.ScriptTransfer()
foreach ($sql in $sqlQueries) {
Write-Message -Level Debug -Message "$sql"
if ($PSCmdlet.ShouldProcess($destInstance, $sql)) {
try {
$null = $destServer.Query($sql, $systemDb)
} catch {
# Don't care - long story having to do with duplicate stuff
# here to avoid an empty catch
$null = 1
}
}
}
} catch {
# Don't care - long story having to do with duplicate stuff
# here to avoid an empty catch
$null = 1
}
}
}
}
}
}