Solved

batch service restart

Posted on 2011-09-08
8
827 Views
Last Modified: 2012-05-12
I'd like to restart a single service on a half dozen Windows 2003/2008 servers or more.  I'd like to do this by a script, and would prefer to have this script query a plain text list of server names.  If not a script a utility that can do the same would be great as well.  I know such a thing can be done easily with a utility like Hyena from SystemTools, but we don't have that tool here.

I'd prefer PowerShell to do this, but have not seen much detailed information on how to perform this type of command remotely and at the same time reference a list of servers in txt or csv format.
0
Comment
Question by:patriots
  • 4
  • 4
8 Comments
 
LVL 70

Expert Comment

by:Chris Dent
ID: 36505980
This example, in PowerShell, reads a list of servers from a file. For each of those servers it restarts the DNS Client service (as an example).
Get-Content YourList.txt | ForEach-Object {
  $Service = Get-WmiObject Win32_Service -Computer $_ -Filter "Name='dnscache'"
  $Service.StopService()
  $Service.StartService()
}

Open in new window

If you want to see the list of services you can play with on a given computer stick with:
Get-WmiObject Win32_Service | Format-List * | more

Open in new window

It's a long list, but you can make "-Filter" use any of the fields you see. For example, a more friendly name for the service name used above:
Get-WmiObject Win32_Service -Filter "Caption='DNS Client'"

Open in new window

HTH

Chris
0
 

Author Comment

by:patriots
ID: 36506341
Thanks, seems to work well.  When you run it, it returns this output at the powershell prompt, but it does what it's supposed to do.  What does this output mean?

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 1
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ReturnValue      : 0
0
 
LVL 70

Expert Comment

by:Chris Dent
ID: 36506381
Ah sorry, forgot about that. Lets make it prettier.
Get-Content YourList.txt | ForEach-Object {
  $Service = Get-WmiObject Win32_Service -Computer $_ -Filter "Name='dnscache'"
  $Stop = $Service.StopService()
  $Start = $Service.StartService()

  If ($Stop.ReturnValue -eq 0 -And $Start.ReturnValue -eq 0) {
    Write-Host "Successfully restarted DNS Client on $_" -ForegroundColor Green
  } Else {
    Write-Host "Failed to stop or start DNS Client on $_" -ForegroundColor Red
  }
}

Open in new window

Better?

Chris
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:patriots
ID: 36506391
This might be more complex, but I can see where it would be helpful to pipe the output results to a log file, with more meaningful output...for example, text like "<service name> restarted successfully on <server name>"

Ultimate goal is that we have a backup service on a varying list of servers that periodically needs to be restarted in order to attempt to fix possible back up issues.  The aim is to make it so we can drop the troulbesome list of servers into the text file, run the script, and have some verification that it succeeded without having to manually check each server.  (Of course if we have to manually check, it more or less defeats the purpose of automating the process.)

Thank you.  I'm a novice at powershell, but anxious to learn it.
0
 

Author Comment

by:patriots
ID: 36506453
The prettier code works even better.  It's almost perfect.  The only thing that's not right on it is that one of the servers in my list I do not have access to b/c my user account happens to not have permission to the system.  It generates this error, but then proceeds to say the service restarted successfully:

Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At D:\scripts\adsmrestart\adsmrestart.ps1:2 char:27
+   $Service = Get-WmiObject <<<<  Win32_Service -Computer $_ -Filter "Name='ServiceName"
    + CategoryInfo          : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Successfully restarted ServiceName on <SERVERNAME>

The script needs to check if "access is denied" and change the message at the end stating such and then it should work perfectly for me.
0
 
LVL 70

Accepted Solution

by:
Chris Dent earned 500 total points
ID: 36506497
Okay, we can extend our code a little. We'll simplify the status we're recording, but that can be whatever you like really.
Get-Content YourList.txt | ForEach-Object {
  # Get the service using WMI (Note: Get-Service is great, but no remote support)
  $Service = Get-WmiObject Win32_Service -Computer $_ -Filter "Caption='DNS Client'"#
  # Stop then Start (each will return a number of things that we can use to figure out if it worked or not)
  $Stop = $Service.StopService()
  $Start = $Service.StartService()
  
  # Figure out if what we tried worked (based on the things we got above)
  If ($Stop.ReturnValue -eq 0 -And $Start.ReturnValue -eq 0) {
    $Status = "Succeeded"
  } Else {
    $Status = "Failed"
  }
  
  # Prepare some output
  New-Object PsObject -Property @{
    Server = $_;
    ServiceName = $Service.Caption;
    Restart = $Status;
  }
}

Open in new window

This leaves us with an Object with a few properties recording the server name, service name and whether or not our restart worked. That's very PowerShelly as we can pass that lot into anything from Export-Csv to ConvertTo-Html to Out-Gridview. For example:
Get-Content YourList.txt | ForEach-Object {
  # Get the service
  $Service = Get-WmiObject Win32_Service -Computer $_ -Filter "Caption='DNS Client'"#
  # Stop then Start
  $Stop = $Service.StopService()
  $Start = $Service.StartService()
  
  # Figure out if what we tried worked
  If ($Stop.ReturnValue -eq 0 -And $Start.ReturnValue -eq 0) {
    $Status = "Succeeded"
  } Else {
    $Status = "Failed"
  }
  
  # Prepare some output
  New-Object PsObject -Property @{
    Server = $_;
    ServiceName = $Service.Caption;
    Restart = $Status;
  }
} | Out-GridView

Open in new window

ConvertTo-Html is perhaps the best if this is running as a scheduled task and you'd like an e-mail or webpage to show how successful things were last time it ran. Is that the kind of thing you had in mind?

Chris
0
 

Author Comment

by:patriots
ID: 36506535
Works perfectly.  Your a genius.  Thanks.
0
 
LVL 70

Expert Comment

by:Chris Dent
ID: 36506541
Cross-posted, this version introduces basic error handling so we can figure out if we can actually do things with the service at all.

I've got comments in the script, but if you want more explanation please do let me know.
$ServiceName = "DNS Client"

Get-Content YourList.txt | ForEach-Object {
  # Get the service
  $Service = Get-WmiObject Win32_Service -Computer $_ -Filter "Caption='$ServiceName'" -ErrorAction SilentlyContinue
  
  # Test to see if that command worked and we have our service. $? is a special variable that tells us if the last command worked or not
  If ($?) {
    # If it worked: Stop then Start
    $Stop = $Service.StopService()
    $Start = $Service.StartService()
  
    # Figure out if what we tried worked
    If ($Stop.ReturnValue -eq 0 -And $Start.ReturnValue -eq 0) {
      $Status = "Succeeded"
    } Else {
      $Status = "Failed"
    }
  } Else {
    # Get-WmiObject didn't work, so...
    $Status = "Failed to connect to service"
  }
  
  # Prepare some output for us
  New-Object PsObject -Property @{
    Server = $_;
    ServiceName = $ServiceName;
    Restart = $Status;
  }
}

Open in new window

Chris
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ADCs have gained traction within the last decade, largely due to increased demand for legacy load balancing appliances to handle more advanced application delivery requirements and improve application performance.
A brief introduction to what I consider to be the best editor for PowerShell.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question