- $serviceState = gwmi Win32_service | ?{ $_.Name -eq "WinRM" }
- While ($serviceState.State -ne 'Stopped')
- {
- $serviceState.State
- Start-Sleep -seconds 5
- Write-host "Process is Running"
- }
While loop
Forum rules
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Do not post any licensing information in this forum.
Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
While loop
I was trying to do a while loop on a service to make an action when the state of the service 'Stopped' and I noticed that loop cant see when the state changes for the service. I wanted to make sure that I am writing this correctly. I am looking at the state of the services and while state does not equal 'Stopped' keep doing the below. When I set the service to 'Running' the while loop never breaks.
Re: While loop
- $p = Stop-Service WinRM -PassThru
- $p.Status
Re: While loop
So is this best practice for this situation? I shouldn't use the while loop? Lastly was the while loop written correctly? I am trying to understand what I did wrong in this situation. It is a simple while loop trying to figure out why it did not work.
Re: While loop
A while loop won't work without re-querying the service. The service.
- $service = Get-WmiObject Win32_service -Filter "Name = 'WinRM'"
- if($service.StopService().ReturnValue -eq 0) {
- Write-Host 'Service stopped'
- }else{
- Write-Host 'Service failed to stop'
- }
Re: While loop
I thought I was querying the service. My issue is the service that I am really querying takes a long time to go down and stays in a Stopping state. I though I could use the while loop to check and if it doesn't change I will just kill the process attached to the service.
Re: While loop
stop-Service waits.
Win32_Service waits.
I don't see why you need to think you have to check. It is only in the GUI that yuo can exit the dialog while the service is still stopping.
Win32_Service waits.
I don't see why you need to think you have to check. It is only in the GUI that yuo can exit the dialog while the service is still stopping.
Re: While loop
I understand they both wait. I am trying to find a way to set a time to kill if the service takes more then 10 minutes to come down.
Re: While loop
Use:
- $service = Stop-Service WinRM -NoWait -PassThru
- $i = 0
- While ($service.State -ne 'Stopped'){
- if($i++ -gt 60){
- Write-Host 'Service not stopped!'
- break
- }
- sleep 1
- $service.Refresh()
- }