none
simple powershell script not working

    Question

  • Below script writes output Running. I go to Services.msc and stop the spooler service and it should write host "Stopped" instead it keeps writing Running. why? Please help me.

    When I stop the spooler service it should write stopped but it is not doing

    $services=Get-Service -Name spooler -ComputerName "DC01"
    while ($services | where {$_.status -eq "running"})
    {
    Write-Host "Running" -ForegroundColor blue
    Start-Sleep -Milliseconds 1000
     if ($services.Status -eq "Stopped")
     {
      Write-Host "Spooler has been stopped"
     }
    }

    Sunday, September 22, 2013 1:33 AM

Answers

  • Hi,

    You're only getting the service status at the very beginning of the script, so the loop has no idea that the service has actually stopped. Give this slight modification of your code a try, which checks the status via Get-Service in the loop as well:

    $services=Get-Service -Name spooler
    while ($services | where {$_.status -eq "running"})
    {
    $services=Get-Service -Name spooler
    Write-Host "Running" -ForegroundColor blue
    Start-Sleep -Milliseconds 1000
     if ($services.Status -eq "Stopped")
     {
      Write-Host "Spooler has been stopped"
     }
    }


    Don't retire TechNet! - (Maybe there's still a chance for hope, over 11,925+ strong and growing)


    • Edited by Mike Laughlin Sunday, September 22, 2013 1:49 AM
    • Marked as answer by asif300 Sunday, September 22, 2013 4:43 AM
    Sunday, September 22, 2013 1:48 AM