|
| 1 | +[CmdletBinding()] |
| 2 | +param ( |
| 3 | + # Instance name to return jobs from |
| 4 | + [Parameter(Mandatory = $false)] |
| 5 | + [string[]] |
| 6 | + $instance_name, |
| 7 | + |
| 8 | + # Name of job or match pattern |
| 9 | + [Parameter(Mandatory = $true)] |
| 10 | + [string[]] |
| 11 | + $job_name, |
| 12 | + |
| 13 | + # Use -match operator name matches. |
| 14 | + [Parameter(Mandatory = $false)] |
| 15 | + [switch] |
| 16 | + $fuzzy_match, |
| 17 | + |
| 18 | + # Job step to start execution from. Zero based indexes. |
| 19 | + [Parameter(Mandatory = $false)] |
| 20 | + [int] |
| 21 | + $step = 0, |
| 22 | + |
| 23 | + # Wait on the job to complete before returning results |
| 24 | + [Parameter(Mandatory = $false)] |
| 25 | + [switch] |
| 26 | + $wait |
| 27 | +) |
| 28 | + |
| 29 | +function Get-SQLInstances { |
| 30 | + param( |
| 31 | + [string[]]$instance_name |
| 32 | + ) |
| 33 | + |
| 34 | + $instancesHolder = New-Object System.Collections.Generic.List[System.Object] |
| 35 | + $stringsToReturn = New-Object System.Collections.Generic.List[System.Object] |
| 36 | + |
| 37 | + # The default instance is referred to in its service name as MSSQLSERVER. This |
| 38 | + # leads many SQLSERVER people to refer to it as such. They will also connect |
| 39 | + # to it using just a '.'. None of these are it's real name. Its real instance |
| 40 | + # name is just the machine name. A named instances real name is the machine |
| 41 | + # name a '\' and the instance name. This little foreach ensures that we are |
| 42 | + # referring to these instances by their real names so that proper filtering |
| 43 | + # can be done. |
| 44 | + |
| 45 | + foreach ($name in $instance_name) { |
| 46 | + switch ($name) { |
| 47 | + {($_ -eq 'MSSQLSERVER') -or ($_ -eq '.')} { [void]$instancesHolder.add($env:COMPUTERNAME) } |
| 48 | + {$_ -eq $env:COMPUTERNAME} { [void]$instancesHolder.add($_) } |
| 49 | + {$_ -notmatch '\\'} { [void]$instancesHolder.add("$env:COMPUTERNAME\$_") } |
| 50 | + default { [void]$instancesHolder.add($name) } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if ($instancesHolder.count -eq 0) { |
| 55 | + [void]$instancesHolder.add($env:computername) |
| 56 | + } |
| 57 | + |
| 58 | + $instanceStrings = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances |
| 59 | + |
| 60 | + # The registry key does not return the real instance names. Again we must |
| 61 | + # normalize these names into their real names so that comparisons can be done |
| 62 | + # properly. |
| 63 | + |
| 64 | + foreach ($string in $instanceStrings) { |
| 65 | + switch ($string) { |
| 66 | + 'MSSQLSERVER' { $string = $env:COMPUTERNAME } |
| 67 | + Default {$string = "$env:COMPUTERNAME\$string"} |
| 68 | + } |
| 69 | + |
| 70 | + foreach ($instance in $instancesHolder) { |
| 71 | + if ($instance -eq $string) { |
| 72 | + [void]$stringsToReturn.add($string) |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + if ($stringsToReturn.count -gt 0) { |
| 78 | + Write-Output $stringsToReturn |
| 79 | + } |
| 80 | + else { |
| 81 | + throw "No instances were found by the name(s) $instance_name" |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +function Get-ServerObject { |
| 86 | + param( |
| 87 | + [string]$instance |
| 88 | + ) |
| 89 | + |
| 90 | + [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") |
| 91 | + |
| 92 | + Write-Output (New-Object Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instance) |
| 93 | +} |
| 94 | + |
| 95 | +function Select-Job { |
| 96 | + param( |
| 97 | + [PSObject]$job, |
| 98 | + [string[]]$jobsToMatch, |
| 99 | + [switch]$fuzzy_match |
| 100 | + ) |
| 101 | + |
| 102 | + |
| 103 | + # This function takes a single SQLServer job object and compares it against |
| 104 | + # the list of names passed into the -job_name parameter of the script to |
| 105 | + # determine if this is a job the user is interested in seeing. If it does |
| 106 | + # not pass the filter represented by that parameter the job is discarded. |
| 107 | + |
| 108 | + foreach ($paramJob in $jobsToMatch) { |
| 109 | + if (!$fuzzy_match) { |
| 110 | + if ($paramJob -eq $job.name) { |
| 111 | + Write-Output $job |
| 112 | + } |
| 113 | + } |
| 114 | + else { |
| 115 | + # Match is a regex operator, and it doesn't like the '\' in domain names. |
| 116 | + if ($job.name -match [regex]::escape($paramJob)) { |
| 117 | + Write-Output $job |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +function New-CustomJobObject { |
| 124 | + param( |
| 125 | + [psobject]$job |
| 126 | + ) |
| 127 | + |
| 128 | + $customObject = @{ |
| 129 | + name = $job.name |
| 130 | + description = $job.description |
| 131 | + enabled = $job.isEnabled |
| 132 | + ownerLoginName = $job.ownerLoginName |
| 133 | + instance = $job.parent.name |
| 134 | + lastRunDate = $job.lastRunDate |
| 135 | + lastRunOutcome = [string]$job.lastRunOutcome |
| 136 | + currentRunStatus = [string]$job.currentRunStatus |
| 137 | + currentRunStep = $job.currentRunStep |
| 138 | + startStepID = $job.startStepID |
| 139 | + currentRunRetryAttempt = $job.currentRunRetryAttempt |
| 140 | + nextRunDate = $job.nextRunDate |
| 141 | + dateCreated = $job.dateCreated |
| 142 | + dateLastModified = $job.dateLastModified |
| 143 | + emailLevel = $job.emailLevel |
| 144 | + operatorToEmail = $job.operatorToEmail |
| 145 | + operatorToNetSend = $job.operatorToNetSend |
| 146 | + operatorToPage = $job.operatorToPage |
| 147 | + category = $job.category |
| 148 | + steps = New-Object System.Collections.Generic.List[System.Object] |
| 149 | + } |
| 150 | + |
| 151 | + foreach ($step in $job.jobSteps) { |
| 152 | + $step = @{ |
| 153 | + name = $step.name |
| 154 | + type = [string]$step.subsystem |
| 155 | + databaseName = $step.DatabaseName |
| 156 | + lastRunDate = $step.lastRunDate |
| 157 | + lastRunDurationSeconds = $step.LastRunDuration |
| 158 | + lastRunOutcome = [string]$step.LastRunOutcome |
| 159 | + lastRunRetries = $step.lastRunRetries |
| 160 | + onFailAction = [string]$step.onFailAction |
| 161 | + onFailStep = $step.onFailStep |
| 162 | + onSuccessAction = [string]$step.onSuccessAction |
| 163 | + onSuccessStep = $step.onSuccessStep |
| 164 | + retryAttempts = $step.retryAttempts |
| 165 | + retryIntervalMinutes = $step.retryInterval |
| 166 | + } |
| 167 | + [void]$customObject.steps.add($step) |
| 168 | + } |
| 169 | + |
| 170 | + Write-Output $customObject |
| 171 | +} |
| 172 | + |
| 173 | + |
| 174 | +$errorReturn = @{ |
| 175 | + _error = @{ |
| 176 | + msg = '' |
| 177 | + kind = 'puppetlabs.task/task-error' |
| 178 | + details = @{ |
| 179 | + detailedInfo = '' |
| 180 | + exitcode = 1 |
| 181 | + } |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +$return = @{jobs = New-Object System.Collections.Generic.List[System.Object]} |
| 186 | + |
| 187 | +$jobs = New-Object System.Collections.Generic.List[System.Object] |
| 188 | +$finishedJobs = New-Object System.Collections.Generic.List[System.Object] |
| 189 | + |
| 190 | +try { |
| 191 | + $SQLInstances = Get-SQLInstances -instance_name $instance_name |
| 192 | +} |
| 193 | +catch { |
| 194 | + $errorReturn._error.msg = 'Cannot detect SQL instance names.' |
| 195 | + $errorReturn._error.details.detailedInfo = $_ |
| 196 | + return $errorReturn | ConvertTo-JSON |
| 197 | +} |
| 198 | + |
| 199 | +foreach ($instance in $SQLInstances) { |
| 200 | + try { |
| 201 | + $sqlServer = Get-ServerObject -instance $instance |
| 202 | + } |
| 203 | + catch { |
| 204 | + $errorReturn._error.msg = "Cannot connect to SQL Instance: $instance" |
| 205 | + $errorReturn._error.details.detailedInfo = $_ |
| 206 | + return $errorReturn | ConvertTo-JSON |
| 207 | + } |
| 208 | + |
| 209 | + foreach ($currentJob in $sqlserver.jobserver.jobs) { |
| 210 | + if ($MyInvocation.BoundParameters.ContainsKey('job_name')) { |
| 211 | + if ($selectedJob = (Select-Job -job $currentJob -jobsToMatch $job_name -fuzzy_match:$fuzzy_match)) { |
| 212 | + [void]$jobs.add($selectedJob) |
| 213 | + $jobName = $selectedJob.jobsteps[$step].name |
| 214 | + if([string]::IsNullOrEmpty($jobName)){ |
| 215 | + $errorReturn._error.msg = ` |
| 216 | + ("No job step found at index {0}. There are {1} steps in the job `"{2}`". Remember that these are zero based array indexes." ` |
| 217 | + -f $step, $selectedJob.jobSteps.count, $selectedJob.name) |
| 218 | + $errorReturn._error.details.detailedInfo = $_ |
| 219 | + return $errorReturn | ConvertTo-JSON |
| 220 | + } |
| 221 | + $selectedJob.start($jobName) |
| 222 | + # It takes the server a little time to spin up the job. If we don't do this here |
| 223 | + # then the -wait parameter may not work later. |
| 224 | + Start-Sleep -Milliseconds 300 |
| 225 | + } |
| 226 | + } |
| 227 | + else { |
| 228 | + [void]$jobs.add($currentJob) |
| 229 | + $jobName = $selectedJob.jobsteps[$step].name |
| 230 | + if([string]::IsNullOrEmpty($jobName)){ |
| 231 | + $errorReturn._error.msg = ` |
| 232 | + ("No job step found at index {0}. There are {1} steps in the job `"{2}`". Remember that these are zero based array indexes." ` |
| 233 | + -f $step, $selectedJob.jobSteps.count, $selectedJob.name) |
| 234 | + $errorReturn._error.details.detailedInfo = $_ |
| 235 | + return $errorReturn | ConvertTo-JSON |
| 236 | + } |
| 237 | + $selectedJob.start($jobName) |
| 238 | + Start-Sleep -Milliseconds 300 |
| 239 | + } |
| 240 | + } |
| 241 | +} |
| 242 | + |
| 243 | +do { |
| 244 | + $done = $true |
| 245 | + $finishedJobs.Clear() |
| 246 | + foreach ($job in $jobs) { |
| 247 | + $job.refresh() |
| 248 | + if ([string]$job.currentRunStatus -ne 'idle') { |
| 249 | + $done = $false |
| 250 | + } |
| 251 | + [void]$finishedJobs.add((New-CustomJobObject -job $job)) |
| 252 | + } |
| 253 | +} while ($wait -and !$done) |
| 254 | + |
| 255 | +$return.jobs = $finishedJobs |
| 256 | + |
| 257 | +return ($return | ConvertTo-JSON -Depth 99) |
| 258 | + |
| 259 | +<# |
| 260 | +.SYNOPSIS |
| 261 | + This script connects to a SQL instance running on a machine and starts agent |
| 262 | + jobs. |
| 263 | +.DESCRIPTION |
| 264 | + This script will connect to SQL instances running on a machine and start agent |
| 265 | + jobs. It allows you to start the job at a specific step. Job steps are |
| 266 | + specified by integer index numbers and indexes are zero based. You can either |
| 267 | + wait for the job to complete, or you can let the task finish and return only |
| 268 | + information indicating the the job is now running. It will always return data |
| 269 | + in JSON format. |
| 270 | +.PARAMETER instance_name |
| 271 | + The name of the instance running on a machine that you would like to connect to. |
| 272 | + Leave blank to get the default instance MSSQLSERVER. |
| 273 | +#> |
0 commit comments