- Add a domain user or group to local administrators with PowerShell - Wed, Mar 19 2014
- Create a list of local administrators with PowerShell - Wed, Mar 5 2014
- Remotely query user profile information with PowerShell - Tue, Nov 26 2013
Restarting a service is quite a common system administration task. If a service has to be restarted on a local computer, we use Service Manager MMC (services.msc). We use the same MMC when a service restart is required on a remote computer. If you want to restart the same service on multiple computers, however, there is no built-in tool. The PowerShell code that I am going to talk about will help you here.
PowerShell is an easy way to restart a service on a remote computer. Though there are multiple ways to restart a service using PowerShell, I prefer the Restart-Service cmdlet. The script I am going to talk about is a wrapper around this cmdlet to get the functionality we need.
This script takes three arguments:
- ComputerName: Here you can provide the list of computers on which to restart the service. This is an optional parameter. If you don’t use it, the script runs against the local computer.
- ServiceName: Name of the service that you want to restart on remote computers. This is a mandatory property.
- OutputDir: Name of the directory where you want to store the output files failedcomputers.txt and successcomputers.txt, which contain the status of the service restart.
You probably know that the Get-Service cmdlet can be used to query remote services. Only a few know that the Start-Service, Stop-Service, and Restart-Service cmdlets can be used to perform respective operations on remote computers even though they don’t have a –ComputerName parameter. The procedure is very simple. Instead of the –ComputerName parameter, we need to use the –InputObject parameter for these cmdlets to stop/start/restart services. The value for –InputObject can be derived using Get-Service. See the code below for more clarity.
$ServiceObj = Get-Service -Name $ServiceName -ComputerName $Computer
-ErrorAction Stop
Restart-Service -InputObj $ServiceObj -erroraction stop
The Get-Service cmdlet with –ComputerName will return an Object reference to the service we are querying. We can input this object to Start-Service, Stop-Service, or Restart-Service to perform the respective actions. The additional –ComputerName parameter is not needed, as I show in the above code. This is the core part of the script. Everything else is a wrapper on top of it.
I also used the Test-Connection cmdlet in the script to see if a computer is reachable before querying for services. I build a custom PsObject to store the output results, which will be displayed on the screen and filtered at the end of the script to save the details in failedComputers.txt and successComputers.txt. By default, these output files are created under c:\. If you want to change the location, use the –OutputDir parameter while running the script.
Samples to restart a service with the PowerShell script
Restart a service on a local computer:
.\Restart-Service –ServiceName dnscache
Restart a service on a remote computer:
.\Restart-Service -ComputerName Comp1 –ServiceName dnscache
Restart a service on Comp1 and Comp2:
.\Restart-Service –ComputerName Comp1, Comp2 -ServiceName dnscache
Take servers list from a text file and restart a service on them:
Get-Content c:\scripts\servers.txt | .\Restart-Service –ServiceName dnscache
This is the output of the command above:
PowerShell - Restart a remote service
For safety, try the script in a lab environment before you run it in production. Hope this script helps. The script is provided as is without warranty of any kind!
Hello Sitaram, I am very interested in this subject as I have always used command line and the “SC” command to accomplish similar.
You mention the creation ow wrappers and output files and I do not see that in your script. I follow the idea of what you are doing but I am missing the syntax. Can you provide a full script exampel rather than the bits and pieces.
Thanks
Mark
Hi Mark, thanks for your comment. You can download complete script using the download link given at the bottom of the article. That has the code for saving the results into text files.
For example, keep all your servers in a single text file named servers.txt and pass it to script like below.
.\restart-service -ComputerName (Get-Content c:\servers.txt) -ServiceName dnscache
Mark,
Great post, I have a follow-up question:
I’d like to re-start a variety of services across a handful of different machines as part of a routine maintenance package. The services are not named the same on any of the machines.
I’d like to pipe in a text file that lists each machine and the service(s) on those machines to re-start. How would I architect that?
Thanks!
-Ben
Hello Sitaram, Thank you for your post. Do you know of a method to pass credentials using this in conjunction with the get-credential commandlet?
@Ben : Assuming you have text file formatted in below way…
computer1:service1
computer1:service2
computer1:service3
computer2:service7
computer3:service4
you can try below code restart the services across computers.
###########
$data = get-content c:\comps-services.txt
foreach($line in $data) {
$computer = $line.split(“:”)[0]
$ServiceName = $line.split(“:”)[1]
$sObj = Get-Service -COmputerName $Computer -Name $ServiceName
Restart-Service -InputObj $sObj
}
###########
This is a very basic version of script. Try if it serves your needs.
its not shows error message on witch server its failed to strt
If you want to pass the credentials to the script itself, then you need to make two changes to the script.
1) Add a new parameter called “Credentials” and make it to prompt/accept credentials object.
[PSCredential]$Credential = Get-Credential
2) You need to add “-Credential $Credential” for Get-Service and Restart-Service cmdlets in the code.
Hope it helps….
Giving Error
PS C:\tmp> Get-Content c:\tmp\servers.txt | .\Restart-Service.ps1 -ServiceName gpssvc
Unexpected token ‘in’ in expression or statement.
At C:\tmp\Restart-Service.ps1:4 char:185
+ begin { } process{ $SuccessComputers = Join-Path $OutputDir “SuccessComputers.txt” $FailedComputers = join-path $Outp
utDir “FailedComputers.txt” $OutputArray = @() foreach($Computer in <<< S
I am getting a success output of IsOnline = True, however the service is not restarting.
Do I need to input the service name anywhere in the script itself?
Exactly what I was after. Thank you very much!
Hey Sitaram. Thanx for your post. I need to restart multiple services(same services) on multiple computer and need to output the data to a text file. is it possible
Aaron, I modified the script under param to change the ServiceName string from
[parameter(Mandatory=$true)]
[string]$ServiceName,
To [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ServiceName = $env:servicename,
Have a txt file with a list of the services you want to restart in the same folder as the script and server txt file and run by
.\Restart-Servcie.ps1 (Get-Content .\Servers.txt) -ServiceName (Get-Content .\Services.txt) -OutputDir .\
This work for our purpose, I just need to format the output now to include the list of services.
Can someone kindly share the corrected script for restarting remote services using the passing credentials parameter with output.txt sucess.
Thanks,
-b
Is this correct?
$data = get-content c:\filename.txt
foreach($line in $data) {
$computer = $line.split(“:”)[0]
$ServiceName = $line.split(“:”)[1]
$Credential = Get-PSCredential domain\username
$sObj = Get-Service -COmputerName $Computer -Name $ServiceName
Restart-Service -InputObj $sObj
}in
$SuccessComputers = Join-Path $OutputDir “SuccessComputers.txt”
$FailedComputers = join-path $OutputDir “FailedComputers.txt” $OutputArray = @() foreach($Computer in <<< S
Can any one help with starting multiple services on multiple remote servers?
Hello Sitaram,
My requirement is below.
We have 6 windows applications servers and 12 application services (All are same services) are running on all servers.
Now application team wants to restart the all services on one server and then after 10 mintus gap it will go for second server and so on…
And post completion of service restart email need to be send to application team email id.
“““““““““`
This is urgent request pls help me to get it done… we have large infra approx more then 1000 servers with all kind of support
Hi Team , can someone help us how to restart services in remote system using input as computer name and service name from text file.
@Santosh – it really depends on how your input file is formatted.
But, here’s an example:
Text file (c:\temp\servicelist.csv)
ServerName, ServiceName
Server1, Spooler
Server2, audioserv
Server3, bits
Script:
David F.
@David – This is working perfectly for me 🙂
How would you amend for adding an output file with service status or success/failure into this script.
Yes, I’m a novice and have tried several ways unsuccessfully to get this going right 🙁
Thanks in Advance
Checking the status is easy – it’s definitely a little more complicated, but does demonstrate several useful things. (The
Add another command below the existing Invoke-Command.
Now, trying to capture a failure to restart is definitely more complicated to do remotely. But, if you are going down that road, there are a few things you can do that would probably be easier. (I haven’t tested this but it should work).
not working not giving any error
Hi Team,
I need help to write powershell script to stop and start services one by one in 2 PC’s
1st services need to stop in PC 1 and wait for 5min then stop service in pc 2 wait for 5min.
Then start 1st service in 1st PC wait for 5min ,then Start service in 2 pc .
Can any one help how to do this.
Why the 5 minute waits?
David F.
@David F.
Hi,
I tried using your command… -> $ServiceList = Import-CSV -path d:\test\servicelist.csv
foreach ($item in $ServiceList) {
Invoke-Command -ComputerName $item.ServerName -ScriptBlock { Restart-Service -name $using:item.servicename }
}
but i run into this error, i’m just new with commands of PS. I just want to restart the services of all our servers at the same time. Because it’s too much of a hassle to remote all 70+ servers just to restart manually. Many thanks
Connecting to remote server ###### failed with the following error message : WinRM cannot process the
request. The following error with errorcode 0x8009030e occurred while using Kerberos authentication: A specified logon session does
not exist.
That makes is sound like these are not domain machines or from an untrusted domain. If that is the case, you’ll need to provide admin credentials on the target machines with the Invoke-Commands
David F.
Very useful information indeed.