Do While Loop

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”})