Stop and restart services remotely using Set-Service

I have a list of 10-15 services that I usually need to restart on 6 servers. I have a script that calls a list of services, then calls a list of servers, and then stops all services:

$Services = Get-Content -Path "C:\Powershell\Services.txt" $Machines = Get-Content -Path "C:\Powershell\Machines.txt" Get-Service -Name $Services -ComputerName $Machines | Set-Service -Status Stopped 

Then I have another separate script to run them again:

 $Services = Get-Content -Path "C:\Powershell\Services.txt" $Machines = Get-Content -Path "C:\Powershell\Machines.txt" Get-Service -Name $Services -ComputerName $Machines | Set-Service -Status Running 

I checked and cannot find a way to put it in one script. As I understand it, Set-Service has the ability to stop, start, and pause services, rather than restarting them at the same time.

Any ideas? I might have missed something completely obvious.

+6
source share
3 answers

To restart services, simply use Restart-Service :

 $Services = Get-Content -Path "C:\Powershell\Services.txt" $Machines = Get-Content -Path "C:\Powershell\Machines.txt" Get-Service -Name $Services -ComputerName $Machines | Restart-Service 

Since, according to the comments, PowerShell v6 removed remote access support from *-Service you need to resort to Invoke-Command for remote execution when starting v6 or newer, for example like this:

 Invoke-Command -Computer $Machines -ScriptBlock { Get-Service -Name $using:Services -ErrorAction SilentlyContinue | Restart-Service } 

or like this:

 Invoke-Command -Computer $Machines -ScriptBlock { Restart-Service $using:Services -ErrorAction SilentlyContinue } 

Another option would be WMI:

 $fltr = ($Services | ForEach-Object { 'Name="{0}"' -f $_ }) -join ' or ' Get-WmiObject Win32_Service -Computer $Machines -Filter $fltr | ForEach-Object { $_.StopService() $_.StartService() } 
+7
source

I'm with Ansgar, this should work

 $Services = Get-Content -Path "C:\Powershell\Services.txt" $Machines = Get-Content -Path "C:\Powershell\Machines.txt" foreach ($service in $services){ foreach ($computer in $Machines){ Invoke-Command -ComputerName $computer -ScriptBlock{ Restart-Service -DisplayName $service} } } 

it's a little dirty but should give you a starting point

Sorry, I forgot to take the time to explain what is happening, so you import each of your txt documents and then process each service and each computer and restart the services.

+2
source

You can try this command with one liner:

 Get-Content .\services.txt | %{Get-WmiObject -Class Win32_Service -ComputerName (Get-Content .\computers.txt) -Filter "Name='$_'"} | %{$_.StopService()}; Get-Content .\services.txt | %{Get-WmiObject -Class Win32_Service -ComputerName (Get-Content .\computers.txt) -Filter "Name='$_'"} | %{$_.StartService()} 
0
source

All Articles