title: PowerShell, simple timed script delivers unreliable results
body: <p>I´m quite new to PowerShell and just a bit more experienced with programming as such.
  The goal of the current excercise our teacher gave us, is basically to code a simple crossroads traffic light.</p>
  <p>I use Windows Forms to display labels, that change colors.
  Now I coded a button, that is supposed to run through the traffic light &quot;phases&quot; once.
  Thanks to prior experiences I went with the method to have a incrementing variable and a Function that checks the value of said variable.</p>
  <p>But the colors turn the intended way once every 4 tries or so, without a recognizable logic to it.
  Am I missing something basic in the way PS reads code and the timing thereof?</p>
  <p>Button, supposed to reset the variable, then increment it, then call the function. Due to the Write-Host I can at lease say that the variable does count to 4 as intended</p>
  <pre><code>$Button1              = New-Object System.Windows.Forms.Button;
  $Button1.Location     = New-Object System.Drawing.Size(300,100);
  $Button1.Text         = &quot;Next Phase&quot;;
  $Window.Controls.Add($Button1);
  $Button1.Add_Click({
      #Set Phase 0, then increment &amp; update Function Phase
      $current_phase = 0;
      Do {
          $current_phase++;
          Write-Host $current_phase;
          Phase_update;
          
      } Until($current_phase -gt 3)
  </code></pre>
  <p>Two of the functions minus some of the color changes, intended to change the colors and then wait a while</p>
  <pre><code>Function Phase_update
  {
      #Phase A
      if ( $current_phase -eq 1 ) 
      {
          $LightTop.ForeColor   = 'red';
      }
      #Phase B
      elseif ( $current_phase -eq 2 ) 
      {
          $LightTop.ForeColor   = 'green'
      }
      Start-Sleep -Seconds 2
  }
  # Show Form
  [void]$Window.ShowDialog()
  </code></pre>
  <p>Thanks in advance for any input, problem specific and in general</p>