functions/Set-DbaJobOwner.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
function Set-DbaJobOwner {
    <#
  .SYNOPSIS
   Sets SQL Agent job owners with a desired login if jobs do not match that owner.
 
  .DESCRIPTION
   This function will alter SQL Agent Job ownership to match a specified login if their
   current owner does not match the target login. By default, the target login will
   be 'sa', but the function will allow the user to specify a different login for
   ownership. The user can also apply this to all jobs or only to a select list
   of jobs (passed as either a comma separated list or a string array).
 
   Best practice reference: http://sqlmag.com/blog/sql-server-tip-assign-ownership-jobs-sysadmin-account
 
  .NOTES
   Tags: Agent, Job
   Original Author: Michael Fal (@Mike_Fal), http://mikefal.net
 
   Website: https://dbatools.io
   Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
   License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 
  .PARAMETER SqlInstance
   SQLServer name or SMO object representing the SQL Server to connect to. This can be a
   collection and receive pipeline input
 
  .PARAMETER SqlCredential
   PSCredential object to connect under. If not specified, current Windows login will be used.
 
  .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 Login
   Specific login that you wish to set as owner - this list is auto-populated from the server. This defaults to 'sa' or the sysadmin name if sa was renamed.
 
  .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 Silent
   Use this switch to disable any kind of verbose messages
 
  .LINK
   https://dbatools.io/Set-DbaJobOwner
 
  .EXAMPLE
   Set-DbaJobOwner -SqlInstance localhost
 
   Sets SQL Agent Job owner to sa on all jobs where the owner does not match sa.
 
  .EXAMPLE
   Set-DbaJobOwner -SqlInstance localhost -Login DOMAIN\account
 
   Sets SQL Agent Job owner to sa on all jobs where the owner does not match 'DOMAIN\account'. Note
   that Login must be a valid security principal that exists on the target server.
 
  .EXAMPLE
   Set-DbaJobOwner -SqlInstance localhost -Job job1, job2
 
   Sets SQL Agent Job owner to 'sa' on the job1 and job2 jobs if their current owner does not match 'sa'.
 
  .EXAMPLE
   'sqlserver','sql2016' | Set-DbaJobOwner
 
   Sets SQL Agent Job owner to sa on all jobs where the owner does not match sa on both sqlserver and sql2016.
 #>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [Alias("TargetLogin")]
        [object]$Login,
        [switch]$Silent
    )

    process {
        foreach ($servername in $SqlInstance) {
            #connect to the instance
            Write-Message -Level Verbose -Message "Connecting to $servername"
            $server = Connect-SqlInstance $servername -SqlCredential $SqlCredential

            # dynamic sa name for orgs who have changed their sa name
            if (!$Login) {
                $Login = ($server.logins | Where-Object { $_.id -eq 1 }).Name
            }

            #Validate login
            if (($server.Logins.Name) -notcontains $Login) {
                if ($SqlInstance.count -eq 1) {
                    throw -Message "Invalid login: $Login"
                }
                else {
                    Write-Message -Level Warning -Message "$Login is not a valid login on $servername. Moving on."
                    Continue
                }
            }

            if ($server.logins[$Login].LoginType -eq 'WindowsGroup') {
                throw "$Login is a Windows Group and can not be a job owner."
            }

            #Get database list. If value for -Job is passed, massage to make it a string array.
            #Otherwise, use all jobs on the instance where owner not equal to -TargetLogin
            Write-Message -Level Verbose -Message "Gathering jobs to update"

            if ($Job) {
                $jobcollection = $server.JobServer.Jobs | Where-Object { $_.OwnerLoginName -ne $Login -and $Job -contains $_.Name }
            }
            else {
                $jobcollection = $server.JobServer.Jobs | Where-Object { $_.OwnerLoginName -ne $Login }
            }

            if ($ExcludeJob) {
                $jobcollection = $jobcollection | Where-Object { $ExcludeJob -notcontains $_.Name }
            }

            Write-Message -Level Verbose -Message "Updating $($jobcollection.Count) job(s)."
            foreach ($j in $jobcollection) {
                $jobname = $j.name

                If ($PSCmdlet.ShouldProcess($servername, "Setting job owner for $jobname to $Login")) {
                    try {
                        Write-Message -Level Verbose -Message "Setting job owner for $jobname to $Login on $servername"
                        #Set job owner to $TargetLogin (default 'sa')
                        $j.OwnerLoginName = $Login
                        $j.Alter()
                    }
                    catch {
                        # write-exception writes the full exception to file
                        Stop-Function -Message "Issue setting job owner on $jobName" -Target $jobName -InnerErrorRecord $_ -Category InvalidOperation
                    }
                }
            }
        }
    }
}