internal/Update-ServiceStatus.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
Function Update-ServiceStatus {
<#
    .SYNOPSIS
    Internal function. Sends start/stop request to a SQL Server service and wait for the result.
 
    .DESCRIPTION
    Accepts objects from Get-DbaSqlService and performs a corresponding action.
 
    .PARAMETER Credential
    Credential object used to connect to the computer as a different user.
 
    .PARAMETER Timeout
    How long to wait for the start/stop request completion before moving on.
     
    .PARAMETER ServiceCollection
    A collection of services from Get-DbaSqlService
     
    .PARAMETER Action
    Start or stop.
     
    .PARAMETER Silent
    Use this switch to disable any kind of verbose messages
   
  .PARAMETER WhatIf
  Shows what would happen if the cmdlet runs. The cmdlet is not run.
   
  .PARAMETER Confirm
  Prompts you for confirmation before running the cmdlet.
 
    .NOTES
    Author: Kirill Kravtsov ( @nvarscar )
 
    dbatools PowerShell module (https://dbatools.io)
    Copyright (C) 2016 Chrissy LeMaire
    This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
    You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
     
    .EXAMPLE
    $serviceCollection = Get-DbaSqlService -ComputerName sql1
    Update-ServiceStatus -ServiceCollection $serviceCollection -Action 'stop' -Timeout 30
    Update-ServiceStatus -ServiceCollection $serviceCollection -Action 'start' -Timeout 30
     
    Restarts SQL services on sql1
     
    .EXAMPLE
    $serviceCollection = Get-DbaSqlService -ComputerName sql1
    $credential = Get-Credential
    Update-ServiceStatus -ServiceCollection $serviceCollection -Action 'stop' -Timeout 0 -Credential $credential
     
    Stops SQL services on sql1 and waits indefinitely for them to stop. Uses $credential to authorize on the server.
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    Param(
        [parameter(ValueFromPipeline = $true, Mandatory = $true)]
        [object[]]$ServiceCollection,
        [parameter(Mandatory = $true)]
        [string[]]$Action,
        [int]$Timeout = 30,
        [PSCredential] $Credential,
        [bool]$Silent
    )
    begin {
        $callStack = Get-PSCallStack
        if ($callStack.Length -gt 1) {
            $callerName = $callStack[1].Command
        }
        else {
            $callerName = $callStack[0].Command
        }
        
        #Prepare the service control script block
        $svcControlBlock = {
            Param (
                $server,
                $service,
                $action,
                $timeout = 30,
                $credential
            )
            #Get WMI service object
            $svcParam = "name='$service'"
            $svc = Get-WmiObject Win32_Service -ComputerName $server -filter $svcParam -Credential $credential
            #Perform $action
            if ($action -eq 'start') { 
                $x = $svc.StartService() 
                $desiredState = 'Running'
                $undesiredState = 'Stopped'
            }
            elseif ($action -eq 'stop') { 
                $x = $svc.StopService() 
                $desiredState = 'Stopped'
                $undesiredState = 'Running'
            }
            #If command was not accepted
            if ($x.ReturnValue -ne 0) { return $x.ReturnValue }
            $StartTime = Get-Date
            #Wait for the service to complete the action until timeout
            while ($true -and $x.ReturnValue -eq 0) {
                try {
                    $svc = Get-WmiObject Win32_Service -ComputerName $server -filter $svcParam -Credential $credential
                }
                catch {
                    throw $_
                    break
                }
                #Succeeded
                if ($svc.State -eq $desiredState) { return 0 }
                #Failed after being in the Pending state
                if ($pending -and $svc.State -eq $undesiredState) { return -2 }
                #Timed out
                if ($timeout -gt 0 -and ((Get-Date) - $StartTime).TotalSeconds -gt $timeout) { 
                    return -1
                }
                #Still pending
                if ($svc.State -like '*Pending') { $pending = $true }
                Start-Sleep 1
            }
        }
    }
    
    process {
        $jobCollection = @()
        #Get priorities on which the service startup/shutdown order is based
        $servicePriorityCollection = $ServiceCollection.ServicePriority | Select-Object -unique | Sort-Object -Property @{ Expression={ [int]$_ }; Descending = $action -eq 'start' }
        foreach ($priority in $servicePriorityCollection) {
            foreach ($service in ($ServiceCollection | Where-Object { $_.ServicePriority -eq $priority })) {
                if ('dbatools.DbaSqlService' -in $service.PSObject.TypeNames) {
                    if ($Pscmdlet.ShouldProcess("Sending $action request to service $($service.ServiceName) on $($service.ComputerName)")) {
                        Write-Message -Level Verbose -Message "Attempting to $action service $($service.ServiceName) on $server."
                        #Start a job per each service
                        $job = Start-Job -ScriptBlock $svcControlBlock -ArgumentList $service.computerName, $service.ServiceName, $action, $Timeout, $credential
                        #Add more properties to the job so that we could distinct them
                        Add-Member -Force -InputObject $job -NotePropertyName ServiceName -NotePropertyValue $service.ServiceName
                        Add-Member -Force -InputObject $job -NotePropertyName ComputerName -NotePropertyValue $service.ComputerName
                        $jobCollection += $job
                    }
                }
                else {
                    Write-Message -Level Critical -Message "Unknown object in pipeline - make sure to use Get-DBAService cmdlet"
                }
            }
        if ($Pscmdlet.ShouldProcess("Waiting for the services to $action")) {
            #Get job execution results
            while ($jobCollection | where { $_.HasMoreData -eq $true }) {
                foreach ($job in ($jobCollection | where { $_.State -ne "Running" -and $_.HasMoreData -eq $true })) {
                    try {
                        $jobResult = $job | Receive-Job -ErrorAction Stop
                        switch ($jobResult) {
                            -2 { Write-Message -Level Warning -Silent $Silent -FunctionName $callerName -Message "The service $($job.ServiceName) on $($job.ComputerName) failed to $action." }
                            -1 { Write-Message -Level Warning -Silent $Silent -FunctionName $callerName -Message "The attempt to $action the service $($job.ServiceName) on $($job.ComputerName) has timed out." }
                            0 { switch ($action) { stop { $actionText = 'stopped' }; start { $actionText = 'started' } } 
                                Write-Message -Level Output -Silent $Silent -FunctionName $callerName -Message "Service $($job.ServiceName) on $($job.ComputerName) was successfully $actionText." 
                            }
                            default { Write-Message -Level Warning -Silent $Silent -FunctionName $callerName -Message ("The attempt to $action the service $($job.ServiceName) on $($job.ComputerName) returned the following error: " + (Get-DBASQLServiceErrorMessage $jobResult))}
                        }
                    }
                    catch {
                        Write-Message -Level Warning -Silent $Silent -FunctionName $callerName -Message ("The attempt to $action the service $($job.ServiceName) on $($job.ComputerName) returned the following error: " + $_.Exception.Message)
                    }
                }
                Start-Sleep -Milliseconds 50
              }
            }
        }
    }
}