How can I get my powershell script to fully wait for the service to be stopped before proceeding?

  arcsight, powershell, scripting, windows

The problem is I have a few java processes that get hung up from time to time and need to be stopped, cleaned up and then started back up. I have the back half of the process all dialed in but when trying to actually stop the service is where I am having some issues. As you will see below I am first force stopping the service and then once it "completes" it waits a bit then checks the service for it’s status and then proceeds with looking for associated processes that we can start to kill but my script seems to jump to quickly in to checking if the service has stopped. My sleep statement doesn’t seem like I can have a value that will work across all my hosts or even on the same host during another service restart period.

$service = "arc_connector_2"
# Force stopping the service before checking and allowing user to kill individual processes 
 related to the service. 

Write-Host("Stopping " + $service)
Stop-Service -Name $service -Force -PassThru


Start-Sleep -Seconds 20
# Validating the service stopped and if not then the ability to kill individual processes kick in.
$servchk = Get-Service -Name $service
if ($servchk.Status -ne 'Stopped'){
    Get-WmiObject win32_process -Filter "name='wrapper.exe'" | Format-List -Property Name, 
Path, ProcessID # Queries the host for any wrapper.exe's if service fails to stop.
    Write-Host ""
    $wp = read-host -Prompt "Enter the process ID of the connector asssociated with this 
wrapper process" 
    Write-Host ""
    Get-WmiObject win32_process -Filter "name='java.exe'" | Format-List -Property Name, Path, 
ProcessID # Queries the host for any java.exe's if service fails to stop. 
    Write-Host ""
    $jp = Read-Host -Prompt "Enter the process ID of the connector associated with this java 
process"
    # Killing the process with a confirmation prompt so the user doesn't mistakenly kill the wrong service.
    Stop-Process -Id $wp -Confirm -PassThru

    # Killing the process with a confirmation prompt so the user doesn't mistakenly kill the wrong service.
    Stop-Process -Id $jp -Confirm -PassThru
    Start-Sleep -Seconds 5
}

Source: Windows Questions

LEAVE A COMMENT