functions/Copy-DbaDatabaseAssembly.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
function Copy-DbaDatabaseAssembly {
    <#
        .SYNOPSIS
            Copy-DbaDatabaseAssembly migrates assemblies from one SQL Server to another.
 
        .DESCRIPTION
            By default, all assemblies are copied. The -Assemblies parameter is auto-populated for command-line completion and can be used to copy only specific assemblies.
 
            If the assembly already exists on the destination, it will be skipped unless -Force is used.
 
            This script does not yet copy dependents.
 
        .PARAMETER Source
            Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater.
 
        .PARAMETER SourceSqlCredential
            Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:
 
            $scred = Get-Credential, then pass $scred object to the -SourceSqlCredential 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 Destination
            Destination Sql Server. You must have sysadmin access and server version must be SQL Server version 2000 or greater.
 
        .PARAMETER DestinationSqlCredential
            Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/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 Assembly
            The assembly(ies) to process - this list is auto-populated from the server. If unspecified, all assemblies will be processed.
 
        .PARAMETER ExcludeAssembly
            The assembly(ies) to exclude - this list is auto-populated from the server
 
        .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.
 
        .PARAMETER Force
            Drops and recreates the assembly if it exists
 
        .PARAMETER Silent
            If this switch is enabled, the internal messaging functions will be silenced.
 
        .NOTES
            Tags: Migration, Assembly
            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
            http://dbatools.io/Get-SqlDatabaseAssembly
 
        .EXAMPLE
            Copy-DbaDatabaseAssembly -Source sqlserver2014a -Destination sqlcluster
 
            Copies all assemblies from sqlserver2014a to sqlcluster, using Windows credentials. If assemblies with the same name exist on sqlcluster, they will be skipped.
 
        .EXAMPLE
            Copy-DbaDatabaseAssembly -Source sqlserver2014a -Destination sqlcluster -Assembly dbname.assemblyname, dbname3.anotherassembly -SourceSqlCredential $cred -Force
 
            Copies two assemblies, the dbname.assemblyname and dbname3.anotherassembly, from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a assembly with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.
 
            In this example, anotherassembly will be copied to the dbname3 database on the server "sqlcluster".
 
        .EXAMPLE
            Copy-DbaThing -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force
 
            Shows what would happen if the command were executed using force.
    #>

    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $true)]
    param (
        [parameter(Mandatory = $true)]
        [DbaInstanceParameter]$Source,
        [PSCredential]$SourceSqlCredential,
        [parameter(Mandatory = $true)]
        [DbaInstanceParameter]$Destination,
        [PSCredential]$DestinationSqlCredential,
        [object[]]$Assembly,
        [object[]]$ExcludeAssembly,
        [switch]$Force,
        [switch]$Silent
    )
    begin {

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

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

        if ($sourceServer.VersionMajor -lt 9 -or $destServer.VersionMajor -lt 9) {
            throw "Assemblies are only supported in SQL Server 2005 and above. Quitting."
        }
    }
    process {

        $sourceAssemblies = @()
        foreach ($database in $sourceServer.Databases) {
            try {
                # a bug here requires a try/catch
                $userAssemblies = $database.Assemblies | Where-Object IsSystemObject -eq $false
                foreach ($assembly in $userAssemblies) {
                    $sourceAssemblies += $assembly
                }
            }
            catch { }
        }

        $destAssemblies = @()
        foreach ($database in $destServer.Databases) {
            try {
                # a bug here requires a try/catch
                $userAssemblies = $database.Assemblies | Where-Object IsSystemObject -eq $false
                foreach ($assembly in $userAssemblies) {
                    $destAssemblies += $assembly
                }
            }
            catch { }
        }

        foreach ($currentAssembly in $sourceAssemblies) {
            $assemblyName = $currentAssembly.Name
            $dbName = $currentAssembly.Parent.Name
            $destDb = $destServer.Databases[$dbName]

            $copyDbAssemblyStatus = [pscustomobject]@{
                SourceServer        = $sourceServer.Name
                SourceDatabase      = $dbName
                DestinationServer   = $destServer.Name
                DestinationDatabase = $destDb
                Name                = $assemblyName
                Status              = $null
                DateTime            = [Sqlcollaborative.Dbatools.Utility.DbaDateTime](Get-Date)
            }


            if (!$destDb) {
                $copyDbAssemblyStatus.Status = "Skipped"
                $copyDbAssemblyStatus

                Write-Message -Level Warning -Message "Destination database $dbName does not exist. Skipping $assemblyName.";
                continue
            }

            if ($Assembly -and $Assembly -notcontains "$dbName.$assemblyName" -or $ExcludeAssembly -contains "$dbName.$assemblyName") {
                continue
            }

            if ($currentAssembly.AssemblySecurityLevel -eq "External" -and $destDb.Trustworthy -eq $false) {
                if ($Pscmdlet.ShouldProcess($destination, "Setting $dbName to External")) {
                    Write-Message -Level Warning -Message "Setting $dbName Security Level to External on $destination"
                    $sql = "ALTER DATABASE $dbName SET TRUSTWORTHY ON"
                    try {
                        Write-Message -Level Debug -Message $sql
                        $destServer.Query($sql)
                    }
                    catch {
                        $copyDbAssemblyStatus.Status = "Failed"
                        $copyDbAssemblyStatus

                        Stop-Function -Message "Issue setting security level" -Target $destDb -InnerErrorRecord $_
                    }
                }
            }

            if ($destServer.Databases[$dbName].Assemblies.Name -contains $currentAssembly.name) {
                if ($force -eq $false) {
                    $copyDbAssemblyStatus.Status = "Skipped"
                    $copyDbAssemblyStatus

                    Write-Message -Level Warning -Message "Assembly $assemblyName exists at destination in the $dbName database. Use -Force to drop and migrate."
                    continue
                }
                else {
                    if ($Pscmdlet.ShouldProcess($destination, "Dropping assembly $assemblyName and recreating")) {
                        try {
                            Write-Message -Level Verbose -Message "Dropping assembly $assemblyName"
                            Write-Message -Level Verbose -Message "This won't work if there are dependencies."
                            $destServer.Databases[$dbName].Assemblies[$assemblyName].Drop()
                            Write-Message -Level Verbose -Message "Copying assembly $assemblyName"
                            $sql = $currentAssembly.Script()
                            Write-Message -Level Debug -Message $sql
                            $destServer.Query($sql,$dbName)
                        }
                        catch {
                            $copyDbAssemblyStatus.Status = "Failed"
                            $copyDbAssemblyStatus

                            Stop-Function -Message "Issue dropping assembly" -Target $assemblyName -InnerErrorRecord $_ -Continue
                        }
                    }
                }
            }

            if ($Pscmdlet.ShouldProcess($destination, "Creating assembly $assemblyName")) {
                try {
                    Write-Message -Level Verbose -Message "Copying assembly $assemblyName from database."
                    $sql = $currentAssembly.Script()
                    Write-Message -Level Debug -Message $sql
                    $destServer.Query($sql,$dbName)

                    $copyDbAssemblyStatus.Status = "Successful"
                    $copyDbAssemblyStatus

                }
                catch {
                    $copyDbAssemblyStatus.Status = "Failed"
                    $copyDbAssemblyStatus

                    Stop-Function -Message "Issue creating assembly" -Target $assemblyName -InnerErrorRecord $_
                }
            }
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Silent:$false -Alias Copy-SqlDatabaseAssembly
    }
}