Solved

Stop and restart service using powershell

Posted on 2014-10-21
38
157 Views
Last Modified: 2014-12-15
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
0
Comment
Question by:dongocdung
  • 15
  • 14
  • 3
  • +3
38 Comments
 
LVL 24

Expert Comment

by:Mohammed Khawaja
ID: 40394573
Do you want it stopped or restarted?
0
 

Author Comment

by:dongocdung
ID: 40394578
I want it to stop so we can do maintenance
0
 
LVL 67

Expert Comment

by:sirbounty
ID: 40394613
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
 
LVL 19

Expert Comment

by:Miguel Angel Perez Muñoz
ID: 40394622
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
 
LVL 37

Expert Comment

by:Neil Russell
ID: 40394624
Could you explain what you mean by Turn off java?
0
 
LVL 67

Expert Comment

by:sirbounty
ID: 40394631
$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
 
LVL 24

Expert Comment

by:Mohammed Khawaja
ID: 40394639
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
 

Author Comment

by:dongocdung
ID: 40395319
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
 
LVL 68

Expert Comment

by:Qlemo
ID: 40395330
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40395366
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
 

Author Comment

by:dongocdung
ID: 40399669
sirbounty - Actually, java is a process. How do I stop java process after I stop netlogon service?
0
 
LVL 37

Expert Comment

by:Neil Russell
ID: 40399702
But stopping the Jave process, if it is running, ONLY stops it for that split second. SOMETHING could start another process straight away.
0
 
LVL 68

Expert Comment

by:Qlemo
ID: 40399721
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40399755
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40399758
I agree with the above, however I don't think that java is one such process...(disclaimer of course: I could be wrong ;^)
0
 

Author Comment

by:dongocdung
ID: 40399850
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40399870
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
 

Author Comment

by:dongocdung
ID: 40399889
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40400010
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:dongocdung
ID: 40400069
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40400084
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
 

Author Comment

by:dongocdung
ID: 40402562
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40403350
Just remove
| sort value -Descending
from the code above...or change -Descending to -Ascending
0
 

Author Comment

by:dongocdung
ID: 40407055
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
 
LVL 67

Accepted Solution

by:
sirbounty earned 500 total points
ID: 40407661
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
 

Author Comment

by:dongocdung
ID: 40411413
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40411784
Try launching powershell from an elevated command prompt.
0
 
LVL 37

Expert Comment

by:Neil Russell
ID: 40411872
If you open task manager, who is the Owner of the Java.exe process?
0
 

Author Comment

by:dongocdung
ID: 40413232
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40413427
Elevate a cmd prompt, and type
taskkill /im java.exe /f

What are the results?
0
 

Author Comment

by:dongocdung
ID: 40413749
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40414131
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
 

Author Comment

by:dongocdung
ID: 40416089
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40416391
Not sure about that one - any errors?
0
 

Author Comment

by:dongocdung
ID: 40449754
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
 
LVL 67

Expert Comment

by:sirbounty
ID: 40449794
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
 
LVL 68

Expert Comment

by:Qlemo
ID: 40450025
Most probably you didn't wait some time between start and stop, or services are depending on each other.
0
 

Author Closing Comment

by:dongocdung
ID: 40500546
Thank you so much for your help
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
"Migrate" an SMTP relay receive connector to a new server using info from an old server.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

707 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

18 Experts available now in Live!

Get 1:1 Help Now