I want to check the status of multiple services on multiple remote servers. And if they are not running, start them. So I thought I would first define which services I want to check for each server.
if ($servername = 'server1') {$services = 'service1','service2','service3','service4'}
if ($servername = 'server2') {$services = 'service5','service6','service7','service8'}
if ($servername = 'server3') {$services = 'service9','service10','service11','service12'}
And then create a function to loop though each server, and check it’s services, depending on the server name.
function check_services {
foreach ($service in 'server1') {
if ((Get-Service -ComputerName server1 -Name $service).Status -ne 'Running') {
Write-Host $service on server1 is not running. Starting it.
Set-Service -ComputerName server1 -Name $service -Status Running
}
else {
Write-Host $service is running on server1
}
}
}
I then realized I will have to create a function for each server I want to check.
How can I create a single function that will go through each server and check it’s corresponding services?
aristosv,
Welcome back to the forum. … long time no see.
Why do you use if statements for that? … and BTW:
In PowerShell the equal sign (=) is the assignment operator. If you want to check for equality you should use -eq.
Why do you think you need a function? … and BTW: Set-Service is used to change the settings of a given service - not to start or restart it. Therefor you should use Start-Service or Restart-Service.
I’d recommend to save the needed information in a structured way - for example a CSV file. Thhen you can iterate with a nested loop of the servers and for each server over the services.
In general: what you’re asking for is a very common and simple task what has been asked a lot of times and already answered a lot of time. You don’t have to re-invent the wheel again. Use your prefered internet search engine to search for examples you can adapt to your particular needs. You will find some even here on PowerShell.org.