Do While Loop

Welcome Forums General PowerShell Q&A Do While Loop

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years, 2 months ago.

  • Author
  • #5646

    Points: 0
    Rank: Member

    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 {$ -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 $ 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"})

The topic ‘Do While Loop’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort