# Copyright (c) 2005 Microsoft Corporation. All rights reserved. # # ServiceControl.ps1 # # This script performs 3 functions: # 1. Saves or removes the state of currently running functions # 2. Stops services that use exchange files so they can be updated # 3. Starts services based on the state taken in step 1 # See the Usage function for details # Disable the confirmation for destructive tasks $confirmPreference = "None" # # "Member variables" for the service control functions # $script:logDir = "$env:SYSTEMDRIVE\ExchangeSetupLogs" $script:serviceStateFile = "$script:logDir\StoppedServices.xml" $script:serviceRegistryDataFile = "$script:logDir\ServiceRegistryData.xml" $script:tempserviceStateFile = "$env:TMP\StoppedServices.xml" $script:tempserviceRegistryDataFile = "$env:TMP\ServiceRegistryData.xml" $script:services = @( ) $script:servicesRegistryData = @( ) $script:previouslyStartedServices = @{ } $script:knownRoles = @( 'AdminTools', 'Bridgehead', 'ClientAccess', 'Gateway', 'Mailbox', 'UnifiedMessaging', 'Monitoring', 'CentralAdmin', 'Critical' ) $script:serviceControlError = $null # DEVS: Put services for your role here $script:servicesToControl = @{} $script:servicesToControl['Common'] = @( 'WinMgmt', 'RemoteRegistry', 'HealthService', 'OnePoint', 'MOM', 'OMCFG' ) $script:servicesToControl['AdminTools'] = @() $script:servicesToControl['ClientAccess'] = @( 'MSExchangeMonitoring', 'MSExchangeIMAP4', 'MSExchangePOP3' , 'MSExchangeADTopology' , 'MSExchangeFDS', 'IISAdmin', 'MSExchangeServiceHost', 'W3Svc', 'MSExchangeRPC', 'MSExchangeMailboxReplication', 'MSExchangeFBA', 'MSExchangeAB', 'MSExchangeProtectedServiceHost' ) $script:servicesToControl['Gateway'] = @( 'MSExchangeMonitoring', 'WorkerService', 'MSExchangeTransport', 'MSExchangeTransportLogSearch', 'MSExchangeEdgeSync', 'MSExchangeAntispamUpdate', 'MSExchangeEdgeCredential', 'MSExchangeServiceHost' ) $script:servicesToControl['Mailbox'] = @( 'MSExchangeMonitoring', 'IISAdmin', 'MSExchangeIS', 'MSExchangeMailboxAssistants', 'MSExchangeSA', 'MSFTESQL-Exchange', 'MSExchangeMailSubmission', 'MSExchMailSubmissionSvc', 'MSExchangeThrottling', 'MSExchangeADTopology' , 'MSExchangeRepl', 'MSExchangeTransportLogSearch', 'MSExchangeRPC', 'MSExchangeServiceHost', 'W3Svc', 'MSExchangeSearch', 'HTTPFilter', 'wsbexchange' ) $script:servicesToControl['Bridgehead'] = @( 'MSExchangeMonitoring', 'AdminService', 'MSExchangeTransport' , 'MSExchangeADTopology' , 'MSExchangeEdgeSync', 'MSExchangeProtectedServiceHost', 'MSExchangeTransportLogSearch', 'MSExchangeAntispamUpdate', 'MSExchangeServiceHost', 'W3Svc' ) $script:servicesToControl['UnifiedMessaging'] = @( 'MSExchangeMonitoring', 'Exchange UM Service' , 'MSExchangeADTopology' , 'MSExchangeFDS', 'MSExchangeUM', 'MSSpeechService', 'MSExchangeServiceHost', 'W3Svc' ) $script:servicesToControl['Monitoring'] = @( 'MSExchangeCAMOMConnector', 'MSExchangeMonitoringCorrelation' ) $script:servicesToControl['CentralAdmin'] = @( 'MSExchangeCentralAdmin', 'MSExchangeMonitoringCorrelation', 'WDSServer', 'MSDTC' ) # List of critical services required for prereqs. $script:servicesToControl['Critical'] = @( 'WinMgmt', 'RemoteRegistry', 'W3Svc', 'IISAdmin' ) # list of installed services, this should be calculated based on the registry values $script:installedRoles = @() # snapin key $script:snapinKey = 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.Exchange.Management.PowerShell.Setup' # setup key $script:setupKey = 'HKLM:\SOFTWARE\Microsoft\ExchangeServer\v14\Setup' # If log file folder doesn't exist, create it if (!(Test-Path $logDir)){ New-Item $logDir -type directory } # Get-ServiceToControl # Returns list of service(s) to control. # Arguments: # $Roles - list of Exchange roles. # $Active - indicates that only non-stopped service should be returned. # Returns: # Service(s) to control. function Get-ServiceToControl ([string[]]$Roles, [switch]$Active) { # 1. Populate full list of services for all roles. & { # 1.a. Get common ones. if (($Roles -notcontains 'Critical') -and ($script:servicesToControl['Common'])) { $script:servicesToControl['Common'] } # 1.b. Get services for each role. $Roles | foreach { if ($script:servicesToControl[$_]) { $script:servicesToControl[$_] } } } | # 2. Eliminate duplicates. sort | unique | # 3. Filter only those which are installed # and (optionally) running. where { $serviceName = $_ # 3.a. Check if installed. # Note the trick of requesting by pattern prevents Get-Service # from failing in case service is not installed. Get-Service "$serviceName*" | ?{$_.Name -eq $serviceName} | # 3.b. If $Active is specified, check that service is not stopped. ?{!$Active -or $_.Status -ne 'Stopped'} } } ############################################################################### # # Service state management functions # These functions are used to determine if a service was running or not before setup started # # SaveServiceState # Saves the state of all services to a well known location # Returns: # void function SaveServiceState { Log "Saving service state to '$script:serviceStateFile'..." get-service | export-clixml $script:serviceStateFile } # SaveServiceRegistryData # Saves the registry data from the Services path # Returns: # void function SaveServiceRegistryData { Log "Saving services registry data" get-itemproperty HKLM:\SYSTEM\CurrentControlSet\Services\* -ea SilentlyContinue | export-clixml $script:serviceRegistryDataFile } # LoadServiceState # Retrieves the previously saved service state # Returns: # void function LoadServiceState { if( test-path $script:serviceStateFile) { Log "Reading service state from '$script:serviceStateFile'..." $script:services = import-clixml $script:serviceStateFile Log ("Loaded state for {0} services" -F $script:services.Length) } elseif(test-path $script:tempserviceStateFile) { Log "'$script:serviceStateFile' not found. Reading service state from temporary location '$script:tempserviceStateFile'..." $script:services = import-clixml $script:tempserviceStateFile Log ("Loaded state for {0} services" -F $script:services.Length) } else { Log "Service state file not present: $script:serviceStateFile" } } # LoadServiceRegistryData # Retrieves the previously saved service registry data # Returns: # void function LoadServiceRegistryData { if( test-path $script:serviceRegistryDataFile) { Log "Reading service registry data from '$script:serviceRegistryDataFile'" $script:servicesRegistryData = import-clixml $script:serviceRegistryDataFile Log ("Loaded state for {0} services registry" -F $script:servicesRegistryData.Length) } elseif(test-path $script:tempserviceRegistryDataFile) { Log "'$script:serviceRegistryDataFile' not found.Reading service registry data from temporary location '$$script:tempserviceRegistryDataFile'..." $script:servicesRegistryData = import-clixml $script:tempserviceRegistryDataFile Log ("Loaded state for {0} services registry" -F $script:servicesRegistryData.Length) } else { Log "Service registry data file not present: $script:serviceRegistryDataFile" } } # RemoveServiceState # Removes previously saved service state # Returns: # void function RemoveServiceState { Log "Removing service state from '$script:serviceStateFile'..." remove-item $script:serviceStateFile -ea SilentlyContinue } # RemoveServiceRegistryData # Removes previously saved service registry data file # Returns: # void function RemoveServiceRegistryData { Log "Removing service registry data from '$script:serviceRegistryDataFile'..." remove-item $script:serviceRegistryDataFile -ea SilentlyContinue } # WasRunning( serviceName ) # Determines if the service was running when the state was recorded # Params: # serviceName - Name of the service to check # Returns: # True if the service existed and was in the running state. # False on any other condition including the service not existing # or starting, but not running function WasRunning([String] $serviceName) { $ret = $false $s = $script:services | where { $_.ServiceName -ieq $serviceName } if( $s.ServiceName -eq $null ) { if( $serviceName -ieq 'MSExchangeADTopology' ) { # Try old name. $s = $script:services | where { $_.ServiceName -ieq 'ADTopologyService' } } elseif( $serviceName -ieq 'MSExchangeMailSubmission' ) { # Try old name. $s = $script:services | where { $_.ServiceName -ieq 'MSExchMailSubmissionSvc' } } elseif( $serviceName -ieq 'MSExchangeMailboxAssistants' ) { # Try old name. $s = $script:services | where { $_.ServiceName -ieq 'MSExchangeMA' } } elseif( $serviceName -ieq 'MSExchangeMailboxReplication' ) { # Try old name. $s = $script:services | where { $_.ServiceName -ieq 'MSExchangeServiceHost' } } } if( $s.ServiceName -eq $null ) { Log "'$serviceName' did not exist." } elseif( $s.Status -eq [System.ServiceProcess.ServiceControllerStatus]::Running ) { Log "'$serviceName' was running." $ret = $true } else { Log "'$serviceName' was not running." } return $ret } ############################################################################### # # Main service control functions # These functions start and stop services for a given server role # # StopServices( roleName ) # Stops services for the specified role # Params: # Roles - name of the role to stop services for # Returns: # True if was able to stop all services for the specified role # False on any error # Notes: # It is not an error to stop services that do not exist because # they may be created in the build that is about to install function StopServices([string[]]$Roles) { Status "Stopping services for '$Roles'..." foreach( $serviceName in (Get-ServiceToControl $Roles -Active) ) { Log "Stopping service '$serviceName'." stop-service $serviceName -Force -ev script:serviceControlError if( $script:serviceControlError[0] -ne $null ) { Log ($script:serviceControlError[0].ToString()) return $false } } return $true } # DisableServices # Disables services for a particular role # Params: # Roles - name of the role to disable services for # Returns: # True if was able to disable all services for the specified role # False on any error function DisableServices([string[]]$Roles) { Status "Disabling services for '$Roles'..." foreach( $serviceName in (Get-ServiceToControl $Roles) ) { Log "Disabling service '$serviceName'." $serviceHandle = get-service $serviceName -ea SilentlyContinue if($serviceHandle -eq $null) { Log "Ignoring service '$serviceName'" } else { set-service $serviceName -startuptype disabled -ev script:serviceControlError if( $script:serviceControlError[0] -ne $null ) { Log ($script:serviceControlError[0].ToString()) return $false } } } return $true } # EnableServices( roleName ) # Enables services for the specified role. We don't need any additional logic to take care # of dependencies between services as all the services are enabled for a role. # Params: # Roles - name of the role to enable services for # Returns: # True, if for all existing services starup type can be restored. False otherwise. function EnableServices([string[]]$Roles) { Status "Enabling services for '$Roles'..." LoadServiceRegistryData foreach( $serviceName in (Get-ServiceToControl $Roles) ) { Log "Enabling service '$serviceName'." $service = get-service $serviceName -ea SilentlyContinue if($service -ne $null) { $serviceRegistryData = $script:servicesRegistryData | where {$_.PSChildName -ieq $serviceName} if( $serviceRegistryData -ne $null ) { switch ($serviceRegistryData.Start) { {$_ -ieq 2} { set-service $serviceName -startuptype automatic -ErrorAction SilentlyContinue -ev setServiceError break } {$_ -ieq 3} { set-service $serviceName -startuptype manual -ErrorAction SilentlyContinue -ev setServiceError break } {$_ -ieq 4} { set-service $serviceName -startuptype disabled -ErrorAction SilentlyContinue -ev setServiceError break } default { # start values 0 and 1 are for Boot and System respectively Log "Only Start values 2,3 and 4 are recognized for Win32 service, '$serviceName' has '$serviceRegistryData.Start'" break } } } else { # this is not an error as the sevice might have just been installed Write-ExchangeSetupLog -Warning "'$serviceName' did not exist, this is not an error as the sevice might have just been installed" } if(($setServiceError -ne $null) -and ($setServiceError[0] -ne $null)) { Log ($setServiceError[0].ToString()) if($servicesNotEnabled -ne $null) { $servicesNotEnabled+=', ' + $serviceName } else { $servicesNotEnabled=$serviceName } } } } if($servicesNotEnabled -ne $null) { Status "Unable to enable service(s): '$servicesNotEnabled'." return $false } return $true } # StartServices( roleName ) # Restores Exchange services and dependents for the specified role # to the state recorded during SaveServiceState # Params: # Roles - name of the role to restore services for # Returns: # True if was able to restore all services for the specified role # False on any error # Notes: # If the saved service state is not available, this function # assumes the services were stared function StartServices([string[]]$Roles, [bool]$IgnoreTimeout = $false) { $ret = $true; Status "Starting services for $Roles..." LoadServiceState [bool]$skipDependents = ($Roles.Count -eq 1) -and ($Roles[0] -eq 'Critical') if ($skipDependents) { Log "Dependent services will be skipped." } else { Log "Starting services and their dependents." } foreach( $serviceName in (Get-ServiceToControl $Roles) ) { $depth = [int]0 if( -not( RestoreServiceAndDependents $serviceName $depth -IgnoreTimeout:$IgnoreTimeout -SkipDependents:$skipDependents) ) { Status "Unable to restore service '$serviceName'." $ret = $false; } } return $ret } # RestoreServiceAndDependents(serviceName, depth) # Recursively start a service and its dependents if they # were started when the snapshot was made # Params: # Args[0] - Name of the service to start # Args[1] - The recursion depth of this call # Returns: # True if was able to restore all services and dependents # False on any error # Notes: # If the saved service state is not available, this function # assumes the services were stared function RestoreServiceAndDependents($ServiceName, $Depth, [bool]$IgnoreTimeout = $false, [bool]$SkipDependents = $false) { Log "($depth) Enter: RestoreServiceAndDependents '$serviceName'." $service = get-service $serviceName -ea SilentlyContinue # Filter out cases where we don't need to start the service if( -Not(WasRunning $serviceName) ) { Log "($depth) $serviceName was not previously running." } elseif( $script:previouslyStartedServices[$serviceName] ) { Log "($depth) Already started $serviceName..." } elseif( $service -eq $null ) { Log "($depth) Ignoring non-existent service '$serviceName'." } else { # We actually need to start this service. Use two steps: # 1. Start the service # 2. Recursively do the same thing for each dependent service # Start the service Log "($depth) Starting $serviceName..." start-setupservice -serviceName $serviceName -ev script:serviceControlError -IgnoreTimeout:$IgnoreTimeout if( $script:serviceControlError[0] -ne $null ) { Log ("{0}: {1}" -f $depth, $script:serviceControlError[0].ToString()) return $false } $script:previouslyStartedServices[$serviceName] = $true if (!$SkipDependents) { # Start its dependents Log ("({2}) {0} has {1} dependents." -F $service.Name, $service.DependentServices.Length, $depth) foreach( $d in $service.DependentServices ) { $newdepth = (1+$depth) if( -not( RestoreServiceAndDependents $d.Name $newdepth $IgnoreTimeout ) ) { Log "($depth) Unable to start dependent of '$serviceName'" return $false } } } } Log "($depth) Exit: RestoreServiceAndDependents '$serviceName'" return $true } ############################################################################### # # Utility Functions # These functions factor out common logic # # IsKnownRole( role ) # Determine if the specified name is a valid role name # Params: # Args[0] - Name of the role in question # Returns: # True if the name is a valid role # False otherwise function IsKnownRole { $role = $Args[0] if( $script:knownRoles -ieq $role ) { Log "$role is a known role" return $true } else { Log "$role is an unknown role" return $false } } # Log( $entry ) # Append a string to a well known text file with a time stamp # Params: # Args[0] - Entry to write to log # Returns: # void function Log { $entry = $Args[0] $line = "[{0}] {1}" -F "ServiceControl.ps1", $entry #add-content -Path "$logDir\ServiceControl.log" -Value $line Write-ExchangeSetupLog -Info $line } # Status( $entry ) # Log and write entry to console # Params: # Args[0] - Entry to write to log # Returns: # void function Status { $entry = $Args[0] Log $entry #write-host $entry } # Usage # Display the usage of this script # Returns: # Void function Usage { write-output 'Usage: ServiceControl.ps1 [,...]' write-output " `tOne of {Start Stop Save Remove}" write-output "`t- Start`tStarts the services for the specified role(s)" write-output "`t- Stops`tStarts the services for the specified role(s)" write-output "`t- Save`tSaves a snapshot of the state of all services" write-output "`t- Remove`tRemoves the previously taken snapshot" write-output " `tOne of {$knownRoles}" write-output "`r`n`tA role only needs to be specified for the start and stop operations." } # GetExchangeInstallPath # Gets the install path for Exchange Server. If Exchange is not installed then # null is returned. # Returns # string function GetExchangeInstallPath { $path = $null if(test-path $script:setupKey) { $msiInstallPath = (get-itemproperty -Path $script:setupKey).MsiInstallPath if($msiInstallPath -ne $null) { $path = [System.IO.Path]::Combine( ` $msiInstallPath, ` 'bin') } } return $path } # GetInstalledBuildVersion # Gets the major build version for Exchange Server. If Exchange is not installed # then 0 is returned. # Returns: # int function GetInstalledBuildVersion { $build = 0 if(test-path $script:setupKey) { $build = $(get-itemproperty -Path $script:setupKey).MsiBuildMajor } return $build } # SetSnapinRegistryValues # Creates the snapin key if not present and sets the values. # Params: # Args[0] - Exchange server install path # Args[1] - Exchange server build version # Returns: # bool (true if snapin key was created, false otherwise) function SetSnapinRegistryValues { $snapinKeyCreated = $false $path = $Args[0] $build = $Args[1] $snapinValues = @{ "ApplicationBase"="$path" "AssemblyName"="Microsoft.Exchange.PowerShell.Configuration, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" "Description"="Setup Tasks for the Exchange Server (v$build)" "CustomPSSnapInType"="Microsoft.Exchange.Management.PowerShell.SetupPSSnapIn" "ModuleName"="$path\Microsoft.Exchange.PowerShell.configuration.dll" "PowerShellVersion"="1.0" "Vendor"="Microsoft" "Version"="8.0.0.0" } if(!(test-path $script:snapinKey)) { new-item -path $script:snapinKey $snapinKeyCreated = $true foreach($setting in $snapinValues.Keys) { Log "Setting $setting to $($snapinValues[$setting])" set-itemproperty -Path $script:snapinKey -Name $setting -Value $snapinValues[$setting] } } return $snapinKeyCreated } # AddSnapins # Adds the required snapins to access start-setupservice and stop-setupservice # Returns: # void function AddSnapins { add-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Setup add-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 } # RemoveSnapins # Removes snapins loaded by AddSnapins # Returns: # void function RemoveSnapins { remove-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Setup remove-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 } # RemoveSnapinRegistry # Removes the snapin key from the registry if it was created by the script # Params: # Args[0] - snapin key was created # Returns: # void function RemoveSnapinRegistry { $snapinKeyCreated = $Args[0] if( $snapinKeyCreated ) { remove-item -path $script:snapinKey } } # CleanupForSnapin # Removes the snapin key and unloads the snapins # Params: # Args[0] - snapin key was created # Returns: # void function CleanupForSnapin { RemoveSnapinRegistry $Args[0] RemoveSnapins } # GetInstalledRoles # Gets the installed roles from the registry and stores the information in script:installedRoles # Returns # Void function GetInstalledRoles { # Exchange might not be installed on the machine, so there won't be an existing # registry. We silentlycontinue on errors. $roleRegistryInfoSet = get-itemproperty HKLM:SOFTWARE\Microsoft\ExchangeServer\v14\* -ea SilentlyContinue foreach( $roleRegistryInfo in $roleRegistryInfoSet ) { switch( $roleRegistryInfo.PSChildName) { {$_ -ieq "AdminTools"} { $script:installedRoles += "AdminTools" Log "Adding to installed roles list: AdminTools" break } {$_ -ieq "EdgeTransportRole"} { $script:installedRoles += "Gateway" Log "Adding to installed roles list: Gateway" break } {$_ -ieq "HubTransportRole"} { $script:installedRoles += "Bridgehead" Log "Adding to installed roles list: Bridgehead" break } {$_ -ieq "ClientAccessRole"} { $script:installedRoles += "ClientAccess" Log "Adding to installed roles list: ClientAccess" break } {$_ -ieq "UnifiedMessagingRole"} { $script:installedRoles += "UnifiedMessaging" Log "Adding to installed roles list: UnifiedMessaging" break } {$_ -ieq "MailboxRole"} { $script:installedRoles += "Mailbox" Log "Adding to installed roles list: Mailbox" break } {$_ -ieq "MonitoringRole"} { $script:installedRoles += "Monitoring" Log "Adding to installed roles list: Monitoring" break } default { # There are other things like 'Hygiene' in the registry as well, so we ignore this # information break } } } } ############################################################################### # # Main # Log "-----------------------------------------------" Log ("* ServiceControl.ps1: {0}" -F $(get-date) ) Log "Performing service control with options: $Args" $ret = $false if ($Args.Length -eq 0) { Status "Must specify an operation" Usage return } if( $Args.Length -ge 2 ) { $roles = $Args[1] foreach( $role in $roles ) { if( -not( IsKnownRole $role ) ) { $ret = $false Status ("Unknown role '{0}'." -F $role) Usage return } } } else { if ($Args[0] -match "Stop|DisableServices|Start|EnableServices") { Status "Must specify one or more roles." Usage break } } $activity = $null write-Progress -Activity 'Service Control' -Id 0 -Status 'In Progress' -PercentComplete 0 switch ($Args[0]) { {$_ -ieq "Save"} { $activity = 'Archiving Service State' write-Progress -Activity $activity -Id 0 -Status 'In Progress' -PercentComplete 10 SaveServiceState SaveServiceRegistryData $ret = $true break } {$_ -ieq "Remove"} { $activity = 'Removing State Archive' write-Progress -Activity $activity -Id 0 -Status 'In Progress' -PercentComplete 10 RemoveServiceState RemoveServiceRegistryData $ret = $true break } {$_ -ieq "Stop" } { $activity = 'Stopping Services' write-Progress -Activity $activity -Id 0 -Status 'In Progress' -PercentComplete 10 # Loop through each role and terminate on error $ret = $true Log "Will stop services for the roles: $roles." if( -not( StopServices $roles ) ) { $ret = $false Status "Unable to stop all services for roles: $roles." } break } {$_ -ieq "DisableServices" } { $activity = 'Disabling Services' write-Progress -Activity $activity -Id 0 -Status 'In Progress' -PercentComplete 10 # Loop through each role $ret = $true Log "Will disable services for the roles: $roles." if( -not( DisableServices $roles ) ) { $ret = $false Status "Unable to disable all services for roles: $roles." } break } {$_ -ieq "Start" } { $activity = 'Stating Services' write-Progress -Activity $activity -Id 0 -Status 'In Progress' -PercentComplete 10 # Loop through each role and terminate on error $ret = $true if( -not( StartServices $roles -IgnoreTimeout $true ) ) { $ret = $false Status "Unable to restore all services for roles: $roles." } break } {$_ -ieq "EnableServices" } { $activity = 'Enabling Services' write-Progress -Activity $activity -Id 0 -Status 'In Progress' -PercentComplete 10 # Loop through each role and terminate on error $ret = $true Log "Will enable services for the roles: $roles." if( -not( EnableServices $roles ) ) { $ret = $false Status "Unable to enable all services for roles: $roles." } break } {$_ -ieq "BeforePatch"} { # This is the set of stuff we need to do before applying a patch # We stop all the services and disable them. Before doing this we need # to store the service state and registry information $ret = $true $path = GetExchangeInstallPath $build = GetInstalledBuildVersion if(($path -eq $null) -or ($build -eq 0)) { $ret = $false Status ("Exchange server is not installed") } else { # Set the snapin registry values so that the script can access start-setupservice # and stop-startupservice $keyCreated = SetSnapinRegistryValues $path $build AddSnapins trap { CleanupForSnapin $keyCreated Write-ExchangeSetupLog -Error $_.Exception break } # Save the service information Log "Saving service and registry data" SaveServiceState SaveServiceRegistryData GetInstalledRoles # Stop and disable the services Log "Stopping services for the following roles: $script:installedRoles" if( -not( StopServices $script:installedRoles ) ) { $ret = $false Status "Unable to stop all services for $script:installedRoles." } elseif( -not( DisableServices $script:installedRoles ) ) { $ret = $false Status "Unable to disable all services for $script:installedRoles." } CleanupForSnapin $keyCreated } break } {$_ -ieq "AfterPatch"} { # Here we do stuff that is required after a patch is applied # We enable services for the installed roles, start the services based on # the data saved and then remove the files that store service related data $ret = $true $path = GetExchangeInstallPath $build = GetInstalledBuildVersion if(($path -eq $null) -or ($build -eq 0)) { $ret = $false Status ("Exchange server is not installed") } else { # Set the snapin registry values so that the script can access start-setupservice # and stop-startupservice $keyCreated = SetSnapinRegistryValues $path $build AddSnapins trap { CleanupForSnapin $keyCreated Write-ExchangeSetupLog -Error $_.Exception break } GetInstalledRoles # Enable and start services Log "Enabling services for the following roles: $script:installedRoles" if( -not( EnableServices $script:installedRoles ) ) { $ret = $false Status "Unable to enable all services for $script:installedRoles." } elseif( -not( StartServices $script:installedRoles ) ) { $ret = $false Status "Unable to restore all services for $script:installedRoles." } # Remove saved service data RemoveServiceState RemoveServiceRegistryData CleanupForSnapin $keyCreated } break } default { Status "Unknown operation: '$_'" Usage break } } write-Progress -Activity $activity -Id 0 -Status 'Completed' -Completed if( $ret -eq $true ) { Log "Script completed succesfully." } else { Log "Script completed with one or more errors." } # E12.108144: Signature goes here # SIG # Begin signature block # MIIa/wYJKoZIhvcNAQcCoIIa8DCCGuwCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUxBTyUvXp94ZEmOFwjl41fElw # pC+gghXYMIIEhTCCA22gAwIBAgIKYQX3HgAAAAAAMjANBgkqhkiG9w0BAQUFADB5 # MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA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