Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

batch service restart

Posted on 2011-09-08
8
Medium Priority
?
832 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 71

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 71

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
Q2 2017 - Latest Malware & Internet Attacks

WatchGuard’s Threat Lab is a group of dedicated threat researchers committed to helping you stay ahead of the bad guys by providing in-depth analysis of the top security threats to your network.  Check out our latest Quarterly Internet Security Report!

 

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 71

Accepted Solution

by:
Chris Dent earned 2000 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 71

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

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

618 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