Search code examples
powershellpowershell-3.0powershell-4.0powershell-remoting

Powershell do while loop script output unexpected


Trying to get the active processes for powershell(example) after every 5 seconds. Running the below script. I killed 2 powershell sessions and the script which is running every 5 seconds doesn't update the active sessions as 3 instead it displays as 5 sessions. please help me where am going wrong

$process = Get-Process powershell* 
$count = $process.count 
Do {
    $count
    sleep -Seconds 5 
} until ($count -eq 1)

Output:

enter image description here


Solution

  • You just need to put your first two statements inside your do block.

    do 
    {
        $process = Get-Process powershell*
        $count = $process.count
        $count
        sleep -Seconds 5
    } until ($count -eq 1)
    

    that way you recalculate $count each time you loop, otherwise the value never changes as you observed.