Solved

batch service restart

Posted on 2011-09-08
8
824 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
 

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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Learn about cloud computing and its benefits for small business owners.
In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

746 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now