title: Powershell $button.add_click executes the whole code inside the add_click block
body: <p>I am new to WPF and event-handling using powershell, what I want to achieve is on click of a button, the progress bar should be shown from 0-100. But when I am running the following piece of code, it computes the whole code inside the add_click block and it only shows the last iteration in the loop.
  I know maybe it is a silly solution, but I do need some help in this. </p>
  
  <pre><code>$syncHash = [hashtable]::Synchronized(@{})
  $newRunspace =[runspacefactory]::CreateRunspace()
  $newRunspace.ApartmentState = "STA"
  $newRunspace.ThreadOptions = "ReuseThread"         
  $newRunspace.Open()
  $newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)
  
  $psCmd = [PowerShell]::Create().AddScript({   
      $XamlPath="C:\Forms\MyFormsv1.xaml" 
      $inputXML = Get-Content -Path $XamlPath
      [xml]$Global:xmlWPF = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^&lt;Win.*', '&lt;Window'
  
      #Add WPF and Windows Forms assemblies
      try{
      Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
      } catch {
      Throw “Failed to load Windows Presentation Framework assemblies.”
      }
  
  
      $syncHash.Window=[Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))
  
      [xml]$XAML = $xmlWPF
  
      $xmlWPF.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
      $Global:synchash.Add($_.Name,$synchash.Window.FindName($_.Name) )}
  
      function tool1_progress{
          $var1=50
          for($index=1 ; $index -le $var1; $index++)
          {            
              [int]$tmpProgNum= ($index/$var1) * 100
              $syncHash.tool1_pb.Value= $tmpProgNum
              $syncHash.consoleOutput.Text=$index
              Start-Sleep -Milliseconds 250 
          }
      }
      $syncHash.myButton.add_click({tool1_progress})  
      $syncHash.Window.ShowDialog() | out-null      
  })
  $psCmd.Runspace = $newRunspace
  $data = $psCmd.BeginInvoke()
  </code></pre>
  
  <blockquote>
    <p>$tool1 is a label. $tool1_pb is a progress bar. $consoleOutput is a
    text box.</p>
  </blockquote>