functions/Copy-DbaAgentJob.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
function Copy-DbaAgentJob {
    <#
        .SYNOPSIS
            Copy-DbaAgentJob migrates jobs from one SQL Server to another.
 
        .DESCRIPTION
            By default, all jobs are copied. The -Job parameter is auto-populated for command-line completion and can be used to copy only specific jobs.
 
            If the job already exists on the destination, it will be skipped unless -Force is used.
 
        .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 Job
            The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.
 
        .PARAMETER ExcludeJob
            The job(s) to exclude - this list is auto-populated from the server
 
        .PARAMETER DisableOnSource
            If this switch is enabled, the job will be disabled on the source server
 
        .PARAMETER DisableOnDestination
            If this switch is enabled, the newly migrated job will be disabled on the destination 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 Job if it exists.
 
        .PARAMETER Silent
            If this switch is enabled, the internal messaging functions will be silenced.
 
        .NOTES
            Tags: Migration, Agent, Job
            Author: Chrissy LeMaire (@cl), netnerds.net
 
            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-DbaAgentJob
 
        .EXAMPLE
            Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster
 
            Copies all jobs from sqlserver2014a to sqlcluster, using Windows credentials. If jobs with the same name exist on sqlcluster, they will be skipped.
 
        .EXAMPLE
            Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -Job PSJob -SourceSqlCredential $cred -Force
 
            Copies a single job, the PSJob job from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If a job with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used.
 
        .EXAMPLE
            Copy-DbaAgentJob -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[]]$Job,
        [object[]]$ExcludeJob,
        [switch]$DisableOnSource,
        [switch]$DisableOnDestination,
        [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

    }
    process {

        if (Test-FunctionInterrupt) { return }

        $serverJobs = $sourceServer.JobServer.Jobs
        $destJobs = $destServer.JobServer.Jobs

        foreach ($serverJob in $serverJobs) {
            $jobName = $serverJob.name
            $jobId = $serverJob.JobId

            $copyJobStatus = [pscustomobject]@{
                SourceServer      = $sourceServer.Name
                DestinationServer = $destServer.Name
                Name              = $jobName
                Status            = $null
                Notes             = $null
                DateTime          = [DbaDateTime](Get-Date)
            }

            if ($Job -and $jobName -notin $Job -or $jobName -in $ExcludeJob) { 
                Write-Message -Level Verbose -Message "Job [$jobName] filtered. Skipping."
                continue
            }
            Write-Message -Message "Working on job: $jobName" -Level Verbose
            $sql = "
                SELECT sp.[name] AS MaintenancePlanName
                FROM msdb.dbo.sysmaintplan_plans AS sp
                INNER JOIN msdb.dbo.sysmaintplan_subplans AS sps
                    ON sps.plan_id = sp.id
                WHERE job_id = '$($jobId)'"

            Write-Message -Message $sql -Level Debug

            $MaintenancePlanName = $sourceServer.Query($sql).MaintenancePlanName

            if ($MaintenancePlanName) {
                $copyJobStatus.Status = "Skipped"
                $copyJobStatus.Notes = "Job is associated with maintenance plan"
                $copyJobStatus
                Write-Message -Level Warning -Message "Job [$jobName] is associated with Maintenance Plan: $MaintenancePlanName"
                continue
            }

            $dbNames = $serverJob.JobSteps.DatabaseName | Where-Object { $_.Length -gt 0 }
            $missingDb = $dbNames | Where-Object { $destServer.Databases.Name -notcontains $_ }

            if ($missingDb.Count -gt 0 -and $dbNames.Count -gt 0) {
                $missingDb = ($missingDb | Sort-Object | Get-Unique) -join ", "
                $copyJobStatus.Status = "Skipped"
                $copyJobStatus.Notes = "Job is dependent on database: $missingDb"
                $copyJobStatus
                Write-Message -Level Warning -Message "Database(s) $missingDb doesn't exist on destination. Skipping job [$jobName]."
                continue
            }

            $missingLogin = $serverJob.OwnerLoginName | Where-Object { $destServer.Logins.Name -notcontains $_ }

            if ($missingLogin.Count -gt 0) {
                $missingLogin = ($missingLogin | Sort-Object | Get-Unique) -join ", "
                $copyJobStatus.Status = "Skipped"
                $copyJobStatus.Notes = "Job is dependent on login $missingLogin"
                $copyJobStatus
                Write-Message -Level Warning -Message "Login(s) $missingLogin doesn't exist on destination. Skipping job [$jobName]."
                continue
            }

            $proxyNames = $serverJob.JobSteps.ProxyName | Where-Object { $_.Length -gt 0 }
            $missingProxy = $proxyNames | Where-Object { $destServer.JobServer.ProxyAccounts.Name -notcontains $_ }

            if ($missingProxy.Count -gt 0 -and $proxyNames.Count -gt 0) {
                $missingProxy = ($missingProxy | Sort-Object | Get-Unique) -join ", "
                $copyJobStatus.Status = "Skipped"
                $copyJobStatus.Notes = "Job is dependent on proxy $($proxNames[0])"
                $copyJobStatus
                Write-Message -Level Warning -Message "Proxy Account(s) $($proxyNames[0]) doesn't exist on destination. Skipping job [$jobName]."
                continue
            }

            $operators = $serverJob.OperatorToEmail, $serverJob.OperatorToNetSend, $serverJob.OperatorToPage | Where-Object { $_.Length -gt 0 }
            $missingOperators = $operators | Where-Object {$destServer.JobServer.Operators.Name -notcontains $_}

            if ($missingOperators.Count -gt 0 -and $operators.Count -gt 0) {
                $missingOperator = ($operators | Sort-Object | Get-Unique) -join ", "
                $copyJobStatus.Status = "Skipped"
                $copyJobStatus.Notes = "Job is dependent on operator $missingOperator"
                $copyJobStatus
                Write-Message -Level Warning -Message "Operator(s) $($missingOperator) doesn't exist on destination. Skipping job [$jobName]"
                continue
            }

            if ($destJobs.name -contains $serverJob.name) {
                if ($force -eq $false) {
                    $copyJobStatus.Status = "Skipped"
                    $copyJobStatus.Notes = "Job already exist on destination"
                    $copyJobStatus
                    Write-Message -Level Warning -Message "Job $jobName exists at destination. Use -Force to drop and migrate."
                    continue
                }
                else {
                    if ($Pscmdlet.ShouldProcess($destination, "Dropping job $jobName and recreating")) {
                        try {
                            Write-Message -Message "Dropping Job $jobName" -Level Verbose
                            $destServer.JobServer.Jobs[$jobName].Drop()
                        }
                        catch {
                            $copyJobStatus.Status = "Failed"
                            $copyJobStatus.Notes = $_.Exception.Message
                            $copyJobStatus
                            Stop-Function -Message "Issue dropping job" -Target $jobName -ErrorRecord $_ -Continue
                        }
                    }
                }
            }

            if ($Pscmdlet.ShouldProcess($destination, "Creating Job $jobName")) {
                try {
                    Write-Message -Message "Copying Job $jobName" -Level Verbose
                    $sql = $serverJob.Script() | Out-String
                    Write-Message -Message $sql -Level Debug
                    $destServer.Query($sql)
                }
                catch {
                    $copyJobStatus.Status = "Failed"
                    $copyJobStatus.Notes = $_.Exception.Message
                    $copyJobStatus
                    Stop-Function -Message "Issue copying job." -Target $jobName -ErrorRecord $_ -Continue
                }
            }

            if ($DisableOnDestination) {
                if ($Pscmdlet.ShouldProcess($destination, "Disabling $jobName")) {
                    Write-Message -Message "Disabling $jobName on $destination" -Level Verbose
                    $destServer.JobServer.Jobs.Refresh()
                    $destServer.JobServer.Jobs[$job.name].IsEnabled = $False
                    $destServer.JobServer.Jobs[$job.name].Alter()
                }
            }

            if ($DisableOnSource) {
                if ($Pscmdlet.ShouldProcess($source, "Disabling $jobName")) {
                    Write-Message -Message "Disabling $jobName on $source" -Level Verbose
                    $job.IsEnabled = $false
                    $job.Alter()
                }
            }
            $copyJobStatus.Status = "Successful"
            $copyJobStatus
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Silent:$false -Alias Copy-SqlJob
    }
}