Stop and restart service using powershell

I am looking for a sample Powershell script to do the following.

Through the use of task manager:
 At 5:00 P.M
. Check java is on or not
. Check netlogon is on or not
. If java is on then turn off
. If netlogon is on then turn off
dongocdungAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mohammed KhawajaManager - Infrastructure:  Information TechnologyCommented:
Do you want it stopped or restarted?
0
dongocdungAuthor Commented:
I want it to stop so we can do maintenance
0
sirbountyCommented:
powershell has a native cmdlet, stop-service, that should work if you can identify the service name.
Netlogon is simply that, but I'm unaware of java using a service.

See http://technet.microsoft.com/en-us/library/ee177005.aspx for more information.
Syntax would be simply
stop-service netlogon

Open in new window

0
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

Miguel Angel Perez MuñozCommented:
You don´t need powershell to do this, is more easy one bat file with:
sc \\machine stop netlogon
sc \\machine stop java_service (I remember it is javaw but not sure)
0
Neil RussellTechnical Development LeadCommented:
Could you explain what you mean by Turn off java?
0
sirbountyCommented:
$services = 'netlogon', 'java'

foreach ($service in $services) {
  $status = get-service $service | select-object -expandproperty status
  if ($status -eq 'Running') {stop-service $service}
}

Open in new window


Then just schedule it via task scheduler.  Filename is powershell.exe.  Arguments would be "-f c:\path to script\scriptname.ps1"
0
Mohammed KhawajaManager - Infrastructure:  Information TechnologyCommented:
Below is the script that you need to schedule to run and I am assuming the Java is a process and is named Java.exe:

$sNetLogon = get-service -Name NetLogon -erroraction silentlycontinue
if $(sNetLogon.Status -eq "Running"){
stop-service $sNetLogon}
$Java = "Java.exe"
$pJava = get-procecess -display $Java -erroraction silentlycontinue
if ($pJava){
stop-process -name $Java}
0
dongocdungAuthor Commented:
sirbounty- The script worked great. how about the same script but checking for whether or not the services are down then turn them on
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Status is 'Stopped', and the cmdlet is stop-service - you should be able to change that yourself. It is important that you gain some understanding of the script - you would not want to ask us for any slight change, will you?
0
sirbountyCommented:
As indicated above, it's simply a flip-flop of the aforementioned script.
$services = 'netlogon', 'java'

foreach ($service in $services) {
  $status = get-service $service | select-object -expandproperty status
  if ($status -eq 'Running') {
      stop-service $service
  } else { 
      start-service $service
  }
}

Open in new window

0
dongocdungAuthor Commented:
sirbounty - Actually, java is a process. How do I stop java process after I stop netlogon service?
0
Neil RussellTechnical Development LeadCommented:
But stopping the Jave process, if it is running, ONLY stops it for that split second. SOMETHING could start another process straight away.
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
I was already wondering ...
Use stop-process -Name Java.exe -Force -EA SilentlyContinue
and Neilsr is correct, you can't make sure the process is not getting started again unless you rename the exe file.
0
sirbountyCommented:
http://www.experts-exchange.com/Q_28541473.html#a40394639 outlines that, but here's the full script that does what you asked:

$elements = @{'service'='netlogon';'process'='java'}

foreach ($item in $elements.GetEnumerator()) {
    try {
        switch ($item.Key) {
            process {
                $result = Get-Process -Name $item.Value -ErrorAction Stop
                if ($result.count -gt 0) {
                    Stop-Process $item.value -Force
                } else {
                    Start-Process $item.Value
                } ; break            
            }
            service {
                $result = Get-Service -Name $item.Value -ErrorAction Stop
                if ($result.Status -eq 'Running') {
                    Stop-Service $item.value -Force
                } else {
                    Start-Service $item.value
                }
            }
        }
    } catch {
        $_.exception
    }
}

Open in new window

0
sirbountyCommented:
I agree with the above, however I don't think that java is one such process...(disclaimer of course: I could be wrong ;^)
0
dongocdungAuthor Commented:
sirbouty- I want to stop service Percussion Rhythmyx server and gatekeeper process manager first then stop Java process. Is this the correct script? ( I received some error. I believe it had to do with missing brackets"

$services = 'Percussion Rhythmyx Server', 'GateKeeper Process Manager'

foreach ($service in $services) {
  $status = get-service $service | select-object -expandproperty status
  if ($status -eq 'Running') {stop-service $service}
}

$elements = @{'process'='java'}

foreach ($item in $elements.GetEnumerator()) {
    try {
        switch ($item.Key) {
            process {
                $result = Get-Process -Name $item.Value -ErrorAction Stop
                if ($result.count -gt 0) {
                    Stop-Process $item.value -Force

}
0
sirbountyCommented:
How are they listed in Get-Service?  Typically most service names are listed without spaces (i.e. I found the first one listed as RhythmyxServer.exe).  

You don't want the $services variable - just add it to the elements as outlined:  if it's a service, add it as such...each key identifies if it's a process or service so the appropriate cmdlet runs against it.
$elements = @{'service='RhythmyxServer';'service'='GateKeeper';'service'='netlogon';'process'='java'}

Open in new window

0
dongocdungAuthor Commented:
The script you sent to me stop java process first. Would you please modify the script so that it stops percussion rythmyx server and gatekeeper first then stop java process ( don't worry about netlogon)
0
sirbountyCommented:
Looks like I botched the hash above anyway - that's what I get for not testing code before posting.
This should work.  Line up your executables as displayed here (if they're correctly named), then the hashtable gets sorted, so that services are tended to first...

$elements = @{'RhythmyxServer'='service';'GateKeeper'='service';'java'='process'}

foreach ($item in $elements.GetEnumerator() | sort value -Descending) {
    try {
        switch ($item.Value) {
            process {
                $result = Get-Process -Name $item.key -ErrorAction Stop
                if ($result.count -gt 0) {
                    Stop-Process $item.key -Force
                } else {
                    Start-Process $item.key
                } ; break            
            }
            service {
                $result = Get-Service -Name $item.key -ErrorAction Stop
                if ($result.Status -eq 'Running') {
                    Stop-Service $item.key -Force
                } else {
                    Start-Service $item.key
                }
            }
        }
    } catch {
        $_.exception
    }
}

Open in new window

0
dongocdungAuthor Commented:
sirbouty - I don't need the part where it say
 
  } else {
                    Start-Process $item.key
                } ; break  

I took that part out and it said it was missing catch.
0
sirbountyCommented:
You probably removed one too many closing brackets "}"...try this:

$elements = @{'RhythmyxServer'='service';'GateKeeper'='service';'java'='process'}

foreach ($item in $elements.GetEnumerator() | sort value -Descending) {
    try {
        switch ($item.Value) {
            process {
                $result = Get-Process -Name $item.key -ErrorAction Stop
                if ($result.count -gt 0) {
                    Stop-Process $item.key -Force
                } ; break            
            }
            service {
                $result = Get-Service -Name $item.key -ErrorAction Stop
                if ($result.Status -eq 'Running') {
                    Stop-Service $item.key -Force
                } else {
                    Start-Service $item.key
                }
            }
        }
    } catch {
        $_.exception
    }
}

Open in new window

0
dongocdungAuthor Commented:
Sirbouty- I promise this will be the last time I ask :)...Would you please flip the script so stopping rhythmyxserver and gatekeeper will run before stop java process?
0
sirbountyCommented:
Just remove
| sort value -Descending
from the code above...or change -Descending to -Ascending
0
dongocdungAuthor Commented:
sirbounty - I tried to remove | sort value -Descending and change -descending to -ascending but it doesn't work.

Java process was still not deleted.
0
sirbountyCommented:
With -descending, it will run against service, service, process from the list provided.
Without the -descending (and oops, there is no -ascending, just remove -descending), it will run process (java), service, service.
If it's not working descending, then it could be a timing issue, a permission/rights issue, etc...

Try placing a wait before the next iteration in the foreach loop:

   } catch {
        $_.exception
    }
#new code inserted below
  start-sleep 10 #wait 10 seconds before continuing
}

Open in new window

If it's rights, you may have to do some troubleshooting to see if the user account running it has the correct permissions to end that process...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dongocdungAuthor Commented:
I put the wait command in there  but java still did not stop. Btw, I ran this script by log into the server under admin account then I typed: powershell -executionpolicy bypass -file "C:\temp\StopService2.ps1"
0
sirbountyCommented:
Try launching powershell from an elevated command prompt.
0
Neil RussellTechnical Development LeadCommented:
If you open task manager, who is the Owner of the Java.exe process?
0
dongocdungAuthor Commented:
Sirbounty - I tried to launch powershell from elevated command prompt as my domain admin and  Java still did not end.

Neilsr - the owner of the java.exe process is System
0
sirbountyCommented:
Elevate a cmd prompt, and type
taskkill /im java.exe /f

What are the results?
0
dongocdungAuthor Commented:
when I elevate a cmd prompt and type taskkill /im java.exe /f, java was ended with the following test "Success: the process "java.exe" with PID 2396 has been terminated.
0
sirbountyCommented:
Finally got a system to test this on...the syntax is not quite right, adjust this line:
including the bold print:

  Stop-Process -name $item.key -Force
0
dongocdungAuthor Commented:
Thanks.

Btw, the first time when I ran it, it worked great. But when I turned the services and the process back on, the script did not work. I logged off, then execute the script and the script worked again.
0
sirbountyCommented:
Not sure about that one - any errors?
0
dongocdungAuthor Commented:
sirbounty - The stop script worked great when I ran it the first time. However, at the second time after I ran the start up script to restart the services and process and then ran the stop script again, the java did not stop.

The stop script only worked the second time when I logged off the server then started running the stop script. Do you why the stop script only run the first time but when I ran it the second time, java.exe did not stop?
0
sirbountyCommented:
I can't see what you're seeing...  It's difficult for me to troubleshoot something that simply doesn't work the way you expect it to.
The best way to help me help you is to give me detailed error information.  If you can check the event logs during those time frames, it may provide additional insight into what's preventing the script from completing.
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Most probably you didn't wait some time between start and stop, or services are depending on each other.
0
dongocdungAuthor Commented:
Thank you so much for your help
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.