How To Change or Restart Service Accounts For Multiple SQL SERVERS AT Once Using Powershell

Опубликовано: 11 Октябрь 2024
на канале: MS SQL DBA Tech Support
1,652
11

Reference Link:
https://devblogs.microsoft.com/script...

To Change the service account
===================================
$serverList = "LENOVO"
$username = "lenovo\user02"
$password = "123"

foreach ($server in $serverList) {
$services = Get-WmiObject -Class Win32_Service -ComputerName $server |
Where-Object { $_.Name -like '*SQL*' -and $_.Name -ne 'SQLBrowser' -and $_.Name -ne 'SQLWriter' -and $_.Name -notlike '*SQLTELEMETRY*' }

foreach ($service in $services) {
$changeServiceStatus = $service.Change($null, $null, $null, $null, $null, $null, $username, $password, $null, $null, $null)

if ($changeServiceStatus.ReturnValue -eq 0) {
Write-Host "$($service.SystemName)\$($service.Name) ... Service account changed successfully" -BackgroundColor Blue -ForegroundColor White
} else {
Write-Host "$($service.SystemName)\$($service.Name) ... Service account change unsuccessful" -BackgroundColor Red -ForegroundColor Yellow
}
}
}
==================================

To Restart the SQL Instances at once
==================
$serverList = "LENOVO"

foreach ($server in $serverList) {
$services = Get-WmiObject -Class Win32_Service -ComputerName $server |
Where-Object { $_.Name -like '*SQL*' -and $_.Name -ne 'SQLBrowser' -and $_.Name -ne 'SQLWriter' -and $_.Name -notlike '*SQLTELEMETRY*' }

foreach ($service in $services) {
Write-Host "Restarting $($service.SystemName)\$($service.Name) ..." -ForegroundColor Yellow

Restart the SQL Server service
Restart-Service -Name $service.Name -Force
}
}
========================

Note:Please Note the all SQL Servers are installed in same machine.
i haven't tested the scenario of where SQL Servers instances installed in multiples systems.