[PowerShell] Script to restart a service and its dependents (and their dependents)

I am trying to write a PowerShell script that will restart the SNMP Service on a server.  The server in question is an HP server that has the various HP Insight agents installed, and some of these depend on the SNMP Service.  One of these services
also depends on one of the other HP Insight services (that in turn depends on SNMP Service).
I can easily write a script that stops and starts the specific services in order, but I don't want to do that.  I like to create scripts that are as flexible as possible.  In this case, I'd like to write a script that takes a service name as input
and can restart that service, including any dependents (and dependents of those dependents, and dependents of those dependents).  They way to do this seems to be recursion, but I simply cannot get it to work correctly.  Here is what I have so far
(just trying to get the services to stop in the correct order):
$MainServiceName = "SNMP"
$ServiceInput = ""
$CurrentService = ""
$Service = ""
function Custom-Stop-Service ($ServiceInput)
Write-Host "Name of `$ServiceInput: $($ServiceInput.Name)"
Write-Host "Number of dependents: $($ServiceInput.DependentServices.Count)"
If ($ServiceInput.DependentServices.Count -gt 0)
ForEach ($Service in $ServiceInput.DependentServices)
Write-Host "Dependent of $($ServiceInput.Name): $($Service.Name)"
If ($Service.Status -eq "Running")
Write-Host "$($Service.Name) is running."
$CurrentService = Get-Service -Name $Service.Name
Custom-Stop-Service $CurrentService
Write-Host "Stopping service $($CurrentService.Name)"
Stop-Service -Name $CurrentService.Name -Force
Else
Write-Host "$($Service.Name) is stopped."
Else
Write-Host "Stopping service $($ServiceInput.Name)"
Stop-Service -Name $ServiceInput.Name
$MainService = Get-Service -Name $MainServiceName
If ($MainService.Status -eq "Stopped")
Write-Host "Service $($MainService.Name) is already stopped."
Else
Custom-Stop-Service $MainService
However, it doesn't work like I expect.  Firstly, it never attempts to stop the SNMP service itself.  Secondly while it does seem to stop all the dependents of SNMP correctly, it tries to stop CqMgHost twice.  Here is the output:
PS C:\Scripts> .\restart_service.ps1
Name of $ServiceInput: SNMP
Number of dependents: 4
Dependent of SNMP: CqMgHost
CqMgHost is running.
Name of $ServiceInput: CqMgHost
Number of dependents: 0
Stopping service CqMgHost
WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
WARNING: Waiting for service 'HP Insight Foundation Agents (CqMgHost)' to finish stopping...
Stopping service CqMgHost
Dependent of SNMP: CqMgStor
CqMgStor is running.
Name of $ServiceInput: CqMgStor
Number of dependents: 1
Dependent of CqMgStor: CqMgHost
CqMgHost is stopped.
Stopping service CqMgStor
Dependent of SNMP: CqMgServ
CqMgServ is running.
Name of $ServiceInput: CqMgServ
Number of dependents: 1
Dependent of CqMgServ: CqMgHost
CqMgHost is stopped.
Stopping service CqMgServ
WARNING: Waiting for service 'HP Insight Server Agents (CqMgServ)' to finish stopping...
WARNING: Waiting for service 'HP Insight Server Agents (CqMgServ)' to finish stopping...
Dependent of SNMP: CpqNicMgmt
CpqNicMgmt is running.
Name of $ServiceInput: CpqNicMgmt
Number of dependents: 1
Dependent of CpqNicMgmt: CqMgHost
CqMgHost is stopped.
Stopping service CpqNicMgmt
Can someone suggest a different script or changes to my script so that it will do what I want?  I know that "Stop-Service -Name SNMP -Force" will work but there are two problems with this: 1) it doesn't record the stop events for the dependents in the
Event Viewer and 2) it doesn't work in reverse ("Start-Service -Name SNMP -Force" nor "Restart-Service -Name SNMP -Force" restart the main service and the other services that depend on SNMP that were stopped).
I'm a little surprised that Restart-Service doesn't behave like the restart function in the Services MMC does, where it easily and reliably handles the stops and starts of not only the service itself, but dependent services and also properly does event logging.

I decided to try to understand why you see layers of dependencies.  I found that on WS2008 R2 HP managemnet does have a second layer.  It does not incluse anything but subservices from HP>  VSC is not  a dependency and, from my research,
should not ever be a dependency.  Of course this does not stop someone from making it a dependency which could create issues.
Here is a recursive function that will display all dependencies of any service or all services,
The code returns the service names in order and can be used to restart all services in dependent order.
function Get-Depends{
[CmdLetBinding()]
Param(
$servicename='SNMP',
$level = 0,
[switch]$infoonly
try{
Write-Verbose $($("`t" * $level)+$servicename)
$servicename
$services=get-service $servicename -ea stop | where{$_.dependentservices}|select -expand dependentservices
if($services){
$services | %{Get-Depends $($_.Name) ($level+1) }
catch{
$_
$depends=Get-Depends -v
The verbose switch displays a hierarchical display of names to ilustrate the dependencies.
jv

Similar Messages

  • Powershell script to Scan Active Directory Attributes for Country and Department ,Then add to Sales Group then add to Distribution list based on Region

    Hey Scripting Guys,
    I have been in and out of Powershell last few years, not that great at it tbh !!! I'm looking for advice on how I can as in Title, Create a Powershell script to Scan Active Directory Attributes for Country and Department ,Then add to Group then add to Distribution
    list based on Region/Country
    I was thinking along the lines of get-aduser -LDAPFilter "(department=SALES France) and adding a where clause for country.
    Any help would be great.
    Dec

    So I have tried a few variations but get errors on both 
    get-aduser -LDAPFilter "(&(department=SALES)(c=us))" | Add-ADPrincipalGroupMembership -MemberOf "testgroup"
    get-aduser -LDAPFilter "(&(department=SALES)(c=fr))" | Add-ADGroupMember -identity "testgroup"
    Add-ADPrincipalGroupMembership : Object reference not set to an instance of an
    object.
    At line:1 char:86
    + get-aduser -LDAPFilter "(&(department=SALES)(c=fr))" | Add-ADPrincipalGroupMe
    mbership <<<< -MemberOf "testgroup"
    + CategoryInfo : NotSpecified: (:) [Add-ADPrincipalGroupMembershi
    p], NullReferenceException
    + FullyQualifiedErrorId : Object reference not set to an instance of an ob
    ject.,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipalGroupMem
    bership

  • Hello  I upgraed my iphone to ios 7 but its dosent work like app stor dosent install any brogram or update programs and its slow and stuck plz help me

    Hello
    I upgraed my iphone to ios 7 but its dosent work like app stor dosent install any brogram or update programs and its slow and stuck plz help me

    My iPhone 5 wouldn't start after I turned it off a few minutes after writing this. It went into recovery mode and I had no choice but to connect to iTunes on PC and restore.
    I restored to factory setting first, just to validate my phone was okay. For a second consecutive iOS update, the  iPhone 5 did not update smoothly while connected to PC and iTunes - I had to retry two times before the progress bar for the update showed. (The exact same problem with the restart occured when I updated to 7.0.4.)
    The good news is that I was ultimately able to restore the iPhone 5 to factory settings while running iOS 7.0.6. I did have a backup from about a month ago lying around and was able to successfully restore with that as well, so the damage done is almost negligible since I had my contacts, notes, mail, etc. backed up to iCloud.
    Once I completed both restores, the sync with iTunes worked fine.

  • How can you get your ipod touch open when you forgot the password and its disabled and not connected to wifi

    How can you get your iPod touch open when you forgot the password and its disabled and not connected to the Internet Connection and you don't want to reset it.

    Disabled
    Place the iOS device in Recovery Mode and then connect to your computer and restore via iTunes. The iPod will be erased.
    iOS: Forgot passcode or device disabled
    If recovery mode does not work try DFU mode.                        
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings        
    For how to restore:                                                             
    iTunes: Restoring iOS software
    To restore from backup see:
    iOS: Back up and restore your iOS device with iCloud or iTunes       
    If you restore from iCloud backup the apps will be automatically downloaded. If you restore from iTunes backup the apps and music have to be in the iTunes library since synced media like apps and music are not included in the backup of the iOS device that iTunes makes.
    You can redownload most iTunes purchases by:                         
    Downloading past purchases from the App Store, iBookstore, and iTunes Store        
    If problem what happens or does not happen and when in the instructions? When you successfully get the iPod in recovery mode and connect to computer iTunes should say it found an iPod in recovery mode.

  • HT201263 my ipad is still asking for the passcode while restoring and its dispalying and an error message

    my ipad is still asking for the passcode while restoring and its dispalying and an error message. what should i do because i cant acess my ipad anymore. someone help me.

    Try and force iPad into Recovery Mode
    1. Disconnect the USB cable from the device, but leave the other end of the cable connected to your computer's USB port.
    2. Turn off the device: Press and hold the Sleep/Wake button for a few seconds until the red slider appears, then slide the slider. Wait for the device to turn off.
    3.While pressing and holding the Home button, reconnect the USB cable to the device. The device should turn on.
    4. Continue holding the Home button until you see the "Connect to iTunes" screen. When this screen appears, release the Home button. iTunes should alert you that it has detected a device in recovery mode. Click OK, and then click Restore to restore the device.
    Note: Data will be lost. You may have to repeat the above many times.

  • HT1923 im trying to unistall itunes and its components and is not letting me/

    im trying to unistall itunes and its components and is not letting me?

    Do you get error messages when doing the uninstalls? If so, what do they say? (Precise text, please.)

  • I bought a new 5s and its front and back camera are not working, showing black image. My phone is IOS 7 updated, and some one insisted that its is software updation problem, and can be resolved by updating to IOS 8. Kindly suggest.

    I bought a new 5s and its front and back camera are not working, showing black image. My phone is IOS 7.1.2 updated, and some one insisted that its is software updation problem, and can be resolved by updating to IOS 8. Kindly suggest.

    I have the same issue on my iPhone 5s
    I've closed the app and re-booted the phone several times but it did not resolve the issue.
    Upgrading to iOS 8.0.2 did not resolve it either.
    Erasing the iPhone and restoring from a backup did not resolve it.
    I'm not sure what else to do.

  • I bought a new iPhone 5s and its front and back camera are not working, showing black image. My phone is IOS 7 updated, and some one insisted that its is software updation problem, and can be resolved by updating to IOS 8. Kindly suggest on this. Wil

    I bought a new iPhone 5s and its front and back camera are not working, showing black image. My phone is IOS 7 updated, and some one insisted that its is software updation problem, and can be resolved by updating to IOS 8. Kindly suggest on this. Will this resolve my issue?

    any advise..?

  • I forgot my password to ipod touch and its disabled and the screen is telling me to connect to itunes

    i forgot my password to my ipod touch and its disabled and the screen is telling me to connect to itunes but i cant do anything else.

    I am having the same issue. My son misplaced his iPod touch and we recently found it under his bed. He then came to me saying he could not remember what his password was and the screen said it was disabled and to connect it to iTunes.  iTunes says it needs to be unlocked.  I have tried turning it off and then holding down the home key and then plugging it in but it fails to go into restore mode.  I have attempted other variations as well (Holding down both the home and sleep buttons, etc but so far nada.  Just curious if anyone else has seen a problem getting it into restore mode and if they found a solution.

  • Using Powershell Script Run simple query in MS Access 2007 and export the results of query to Excel

    Hi Experts,
    I have a Access 2007 DB file and 2 Big tables inside that (bigger than the size that can be easily handled by MS Excel 2007).
    My requirement is automate using powershell scripts the below things.
    1. Create a SQL query in Access DB and save that in access DB
    2. Run the saved query and export the result in excel sheet where I can create the charts and Pivots. Thanks in advance
    Prajesh

    Do you have to use the Access query, couldn't you just recreate the query in Powershell?  Here's a link with good info that references an existing script for querying an Access database:
    http://blogs.technet.com/b/heyscriptingguy/archive/2009/08/13/hey-scripting-guy-can-i-query-a-microsoft-access-database-with-a-windows-powershell-script.aspx
    Once you have your dataset you can pipe it to
    Export-Csv -NoType c:\pathtofile\output.csv

  • I have tried suggestions found on this website from other Ipod Classic users without success. I cannot get my Ipod Classic to sync any more - have tried on 3 computers with different OS's. Apple have tested Ipod and its lead and pronounced it OK.

    This is the third time of writing this on your Apple Support Communities!  My Ipod Classic will not sync.  I have had it checked over at an Apple Genius Bar and also its lead - they say it is OK.   I have had my computer checked at the place that built it for me (Windows 7 desktop when I found Windows 8 childish and irritating).  After collecting it, I again had the Ipod symbol back on my library page, which was a step forward.  However, the Ipod still won't sync.
    I have tried other USB ports.  I have tried removing Itunes from computer and downloading it again - with the latest version of course.  I have tried authorising my computer.   I have tried resetting the Ipod.  I have tried ringing the Apple helpline at vast expense - the first assistant was helpful and went through a number of procedures before suggesting I removed and replaced Itunes and then rang back after doing this.  I was given a reference number to quote so that I wouldn't need to go through the whole rigmarole again with another assistant.  But, unfortunately, I got an extremely offensive young man who more or less called me a liar when I quoted the job number I had been given.  He flatly refused to accept that I had already spent ages on the phone that afternoon and said that my last call to Apple, to which the reference number referred, had been in November 2011.  When I asked to speak to a manager, he put the phone down for ages and left me paying for minutes, just waiting.  I put the phone down eventually and rang back, got this person again, and again asked to speak to a manager, whereupon the phone was put down on me.  Needless to say, I am not keen to try this phone service again in a hurry.  But I do desperately want to be able to download my Economist in audio podcasts, which I have been without for a whole month now.  Please can someone knowledgeable take pity and help me?  By the way, what does IOS mean? (I thought IO stood for operating system, but am flummoxed by the S on the end.  I have a newly built computer using Windows 7, the latest updated version.

    chicx wrote:
    This is the third time of writing this on your Apple Support Communities!
    Not with your current user id.
    Far too much uneccesary information in your post, which only confuses things, a vast amount!
    Let's start with iTunes.
    Have you updated iTunes to 11.1.5, because the previous version did appear to have an issue about seeing iPods?
    With iTunes 11.1.5 installed, look in Edit/Preferences/Devices, (or use the ALT key, followed by the E key and then the F key) and make sure that the box named Prevent iPods, iPhones and iPads from syncing automatically does not have a tick in the box.
    Once you have doen those two things, check to see if the iPod is seen by iTunes.
    chicx wrote:
    By the way, what does IOS mean? (I thought IO stood for operating system, but am flummoxed by the S on the end.
    Really?
    OS stands for Operating System. (In computer speak, IO means Input/Output.)
    iOS originally stood for iPhone Operating System, but it now refers to the iPod Touch and iPhone. The iPod Classic, which you have listed in your profile as your iPod, does not use iOS.
    I assume that you have been listening to the Podcast in your iTunes on the computer as you cannot transfer it to your iPod. It's what I'd do.

  • Why when i convert to black and white and change, contrast, exposure etc and get it right in preview i open it and its brighter and looks different to the preview?

    The images also look different in preview and when i upload them to adobe Revel but when i put them back in photoshop they look Ok.

    I convert, in raw to black and white and add sharpness and clarity theirs and a few other options Temp etc if need be. Then i open them into photo shop as black and white. There i place around with the exposure setting but as you do it you have the preview button clicked so you see what the finished photo will look like. When i hit change normally the photo changes and looks like it was in the preview.But now with out changing any settings in photoshop, as i change the photo the preview is different when i click ok to make the changes. This comes and goes in photoshop and its getting a bit frustrating as i do a lot of black and white photos and have been doing for years but i am having this problem over the last 6 months.
    No i haven't changed colour settings i have photoshop on the preset settings.
    'Preview" when you are changing contrast etc their is the preview option so it shows in photoshop what the changes will be. But what i see when i am changing it is different when i open it. make be a point brighter or not as contrasty as i see it as i am changing the settings.

  • Comcast and its Billing and Payment system

    Now I will start by saying... I am not happy at all with comcast.... and seeing as how I have been a customer since 2006; why would you treat you customers with such DISRESPECT and not take OWNERSHIP of any actions a customers experiences because of your company. I was told by one of your reps on Friday and I quote "JUST DISREGARD THAT" Here is what I was told to DISREGARD....... I checked my bank account to find this submitted to my bank..... which I did not initiate nor authorize.  I immediately called comcast and after waiting on hold about 15 minutes; only to be given a phone number to call supposedly COLLECTIONS .....by the first female rep.... that was inaccurate..... after waiting on hold about 10 minutes... and was given another 877 number ... and ended up calling comcast back again... the rep asked what I was calling about. I explained...... Why a payment was processed on my bank account for this amount... that I did not set-up. He proceeded to say.. I see that you have a payment set up for the 15th in an amount different from this... and I said that is correct. That is the only payment I set up... so why is this payment being processed on my account. He then asks.. where do I see it... I stated... ON MY BANK ACCOUNT.... I am sitting here looking at it.... HE SAYS "just disregard it" that is not in our system So you mean to tell me that a payment with your company name on it... that has OVERDRAWN my account should just be DISREGARDED...... and even if it was avaialable... I should just DISREGARD it..... despite the FACT that I did not INITIATE or AUTHORIZE this......As I see I was getting nowhere with this person.... I then asked him to search his system for the confirmation number...... he replies.... it is not in the system...... I ended the call with thanks for nothing and I will be searching for another carrier to obtain service from. I called my bank...... after about 3 or 4 transfers they finally credited the overdraft fee, reversed the charge from COMCAST... and restricted my account.... Now I have no money... no access to any money, can't make withdrawals, can't write a check, etc......any money I had to last me til my paycheck is LOCKED UP...because of this mess.....  THANKS ALOT COMCAST..... for taking OWNERSHIP ^ ^ ^ ^ ^ ^ ^ ^ I have bee laid off since 2011 and just got a job a few weeks ago.... but have managed to scrape and scrounge to keep my service on so that I can WORK and earn a living...... and your REP tells me to just DISREGARD a payment for more than my past due coming through my bank account and overdrawing it... to the point where a FRAUD CLAIM had to be filed and my account LOCKED. The payment I set up on Monday with a female rep is the FIRST time I have ever... gave my bank information to comcast.... now you tell me what is going on..........? Then I wake up to this email TODAY! I have not REQUESTED or made any changes to my account.    AND where are my CREDITS for NONE WORKING services.... that caused me to have to release 3 days of WORK HOURS..... due to this NONE WORKING SERVICE that I struggle to pay every month. I was told I would be credited for the days my service wasn't working and that has not HAPPENED...... yet I get all of the above......... I would leave two choice words..... but that would just get this post DELETED... which it may anyway.......

    I think we all need to send letter/emails to the FCC Federal Communications Commissionwww.fcc.gov/‎.  I must say Comcast is definitely the worse & doesn't care about their customers.  Approximately three days ago I went to pay my bill, after getting my paycheck. Signing into comcast,  I look on my account. The account showed no payments due.  So, I thought well I must have paid as sometimes I pay in advance.  Today I get a notice that states I am past due.  I wanted to send an email to billing as they are not available today (Sunday) but I wasn't able to find an email address. I got on Comcast chat & asked the rep for an email for a complaint to billing.  He told me to post it on forum. I asked again, don't you have an email for this?? And he told me once more to post on the forum.  NOW WHAT ABOUT THAT CUSTOMER SERVICE.  Not only that they are requiring you to have a digital adapter (box) when having basic cable & you have a HD TV just so they can charge you for the box & continue to raise the monthly charges/fees.  No matter how we try to keep our cost down on a limited budget, comcast finds a way to increase there fees.

  • Re: Comcast and its Billing and Payment system

    Comcast just screwed me too. I'm unhappy enough to change to another provider. I just moved from a very big house to a small apartment and had an outstanding balance from my previious address. I was working overtime and intending to pay the bill down over the next couple of months. I spoke with Comcast reps on 6/2 and 6/6, and told them I couldn't make a payment until the 10th or 11th and that it would be for $200, with the balance to be paid on the 16th. When I went to make the payment on the 16th, my balance was far less than I thought. I thought it had been adjusted so I paid it off. I looked at my checking account today and it was overdrawn! I couldn't figure out why until I looked at my online statement. To my horror, Comcast had debited my account for a whopping $509 on the 11th! I DID NOT AUTHORIZE THAT PAYMENT! I called today and the rep from the "collection department" looked at my account and confirmed there was no indication I had authorized that much to be taken from my account. Frankly, I would've preferred they shut my service off than to pillage my checking account like that -- there are bills I can't pay now.  She also claimed a supervisor wasn't available, and she would leave a message for one. Well, they can take their time getting back to me because I submitted a complaint to the FCC today -- they can explain it to them. I'm SO ticked off!rhondasag wrote:
    Thank you i=am-nerdburg.... that contact helped me out tremendously and explained everything that happened....... 

    This situation has been resolved satisfactorily. After the FCC contacted comcast a man from corporate called & said he'd listen to the recordings. The money which was debited was back in my account within 48 hours & I was also given a generous credit on my account.

  • I forgoy my ipod passcode and its disabled and says connect to itunes

    I forgot the passcode to my ipod and now its disabled and said connect to itunes.How do I reset it ?

    If you are unable to restore, then type "unable to restore" into the search bar at the top of this page by Support and read the resulting help article.

Maybe you are looking for