Sometimes you need to kill every damn windows service on a machine. To reinstall some binaries or running updates. Yes it’s indicative of a deeper problem. But darn it, sometimes it has to happen.
Credit to Dead Platypus for cooking this one up:
$RetryCount = 2
$ServicesToStop =
'Service1',
'Service2',
'Service3',
'Service4',
'Service5',
'Service6',
'Service7',
'Service8'
foreach ($ServiceName in $ServicesToStop) {
$ServiceStopped = $false
$ServiceStopTries = 0
# It's time to go
while (-Not $ServiceStopped -And $ServiceStopTries -lt $RetryCount) {
$ServiceStopTries++
write-host "Stopping service $ServiceName. Attempt $ServiceStopTries." -ForegroundColor Green
try {
#Stop the thing
Stop-Service -Name $ServiceName -ErrorAction Stop -Force -NoWait
}
catch { }
$Service = Get-Service -Name $ServiceName
# Validate that i has indeed stopped
if ($Service.Status -eq "Stopped") {
$ServiceStopped = $true
}
else {
Start-Sleep -s 5
}
}
# It wasn't a question
if (-Not $ServiceStopped) {
$Id = Get-WmiObject -Class Win32_Service -Filter "Name LIKE '$ServiceName'" |
Select-Object -ExpandProperty ProcessId
write-host "Service $ServiceName could not be stopped. Killing process with id $Id" -ForegroundColor Red
#Kill the process
Stop-Process -PassThru -Id $Id -Force
Start-Sleep -s 5
}
$ServiceStopStartTime = Get-Date
while (-Not $ServiceStopped -And $ServiceStopStartTime -gt (Get-Date).AddMinutes(-60)) {
$Service = Get-Service -Name $ServiceName
if ($Service.Status -eq "Stopped") {
$ServiceStopped = $true
}
else {
Start-Sleep -s 5
}
}
# You win this time
if (-Not $ServiceStopped) {
write-error "Service $ServiceName could not be stopped and its process with id '$Id' could not be killed" -ForegroundColor Red
exit 1
}
}