Author Posts

January 1, 2012 at 12:00 am

by spoony123 at 2013-03-10 03:56:30

Hi All – New member here. Just having a go with Do While Loops, when i use the below code i would have expected the word "test" to keep being created but it only does it once, as i understand the while criteria would always be true (until service stops of course) so the Do would keep happening?. Obviously missed something fundamental here – can you guys advise

do {write-host "test"}

while (Get-Service | Where-Object {$_.name -eq "Application Experience" -and $_.status -eq "Started"})

by spoony123 at 2013-03-10 04:12:32

Think i have answered my own question using this code

do {write-host "Application Service Stopped"}
until (Get-Service | Where-Object {$_.Displayname -eq "Application Experience" -and $_.status -eq "Running”})

write-host "started"

This does the job. Thanks

by MasterOfTheHat at 2013-03-11 14:18:21

I assume you wanted to initiate a service start command and then display "Application Service Stopped" until the service was up and running? As you figured out, you were using $_.name instead of $_.DisplayName and "Started" instead of "Running".

Btw, if you wanted to use a do... while loop instead of your do... until, you could have used the code below. The difference is the $_.Status conditional in the Where-Object command.
do {
"Application Service Stopped"
}
while (Get-Service | Where-Object {($_.DisplayName -eq "Application Experience") -and ($_.Status -ne "Running")})

You could also tweak it a little bit to use filtering on the Get-Service command. Probably doesn't make much difference in this case, follows the "filter early" practice.
do {
"Application Service Stopped"
}
while (Get-Service -DisplayName "Application Experience" | Where-Object {$_.Status -ne "Running"})