Skip to content

Instantly share code, notes, and snippets.

@tkouba
Created February 7, 2024 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkouba/7bc68e3f64d48e179aa054486665397a to your computer and use it in GitHub Desktop.
Save tkouba/7bc68e3f64d48e179aa054486665397a to your computer and use it in GitHub Desktop.
Stop services managed by the cluster but not owned by the current node (unexpectedly started)
<#PSScriptInfo
.VERSION 1.1
.GUID 872d1af1-6a2c-4c71-be96-4b230a8e4a5f
.AUTHOR Tomas Kouba
.COMPANYNAME
.COPYRIGHT (c) 2022-24 . All rights reserved.
.TAGS Cluster
.LICENSEURI https://opensource.org/license/mit/
.PROJECTURI
.ICONURI
.EXTERNALMODULEDEPENDENCIES FailoverClusters
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
#>
<#
.SYNOPSIS
Stop services in cluster resources on inactive node.
.DESCRIPTION
Selects services which is running and not owned by current node and stop them.
.INPUTS
NONE
.OUTPUTS
NONE
.EXAMPLE
C:\PS> .\Stop-ClusterServices
.NOTES
Version : 1.1, 2024-02-07
Requires : PowerShell, FailoverClusters
.LINK
#>
[CmdletBinding()]
PARAM(
)
PROCESS {
# Selects cluster groups which are not owned by current node
# then select resources with type 'Generic Service'
# then select 'Running' services
# and stop them
# Get cluster resources from current cluster and filter only "Generic Service" and "Running" state
[System.Collections.ArrayList]$services = ((Get-ClusterGroup | Where-Object {$_.OwnerNode -ne $env:COMPUTERNAME} | Get-ClusterResource) | Where-Object {$_.ResourceType -eq 'Generic Service'} | Get-ClusterParameter -Name ServiceName).Value | Where {$null -ne $_} | Get-Service | Where-Object {$_.Status -eq 'Running'}
# Any service stopped
$any = $false
# Run count
$i = 0
do
{
$i = $i + 1
Write-Debug "Run $($i)"
$any = $false # reset any
foreach ($s in $services)
{
# $s is still running and do not have running dependencies (we assume, that dependecies will be stopped late
if (($s.Status -eq 'Running') -and ((($s.DependentServices | Get-Service | Where-Object {$_.Status -eq 'Running'}).Count) -eq 0))
{
Write-Information -MessageData "Stopping service $($s.DisplayName) ($($s.Name))" -InformationAction Continue
$s | Stop-Service
$any = $true # any service has been stopped, next run
}
}
} while ($any -and $i -le ($services.Count + 5)) # use $any only would start neverending loop, so we are using $i as counter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment