Mike
Mike

Reputation: 164

Is it possible to run a loop within a ButtonClick in Powershell?

I am experimenting with a Button ClickEvent and am stuck, while trying to implement a do-until loop.

It seems to me, that as soon as the code comes to the Do, it stops.

Add-Type -assembly System.Windows.Forms

Clear-Host

$Script:i = 0

# MainForm

$MainForm = New-Object System.Windows.Forms.Form
$MainForm.Size = New-Object System.Drawing.Size (600,600)
$MainForm.Text ='Test'
$MainForm.StartPosition = "CenterScreen"
$MainForm.AutoSize = $true
$MainForm.BringToFront()
$MainForm.BackColor = 'Gray'


# Vocabulary

$Label = New-Object System.Windows.Forms.label
$Label.Location = New-Object System.Drawing.Size (150,200)
$Label.Size = New-Object System.Drawing.Size (250,200)
$Label.Font = New-Object System.Drawing.Font ("Times New Roman",16, 
[System.Drawing.FontStyle]::Bold)
$Label.BackColor = 'Transparent'
$Label.ForeColor = "Blue"
$Label.Text = 'This is some text'
$MainForm.Controls.Add($Label)


$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size (200,400)
$Button.Size = New-Object System.Drawing.Size (200,75)
$Button.Font = New-Object System.Drawing.Font ("Arial",10, 
[System.Drawing.FontStyle]::Bold)
$Button.Text = 'Test'
$MainForm.Controls.Add($Button)
$ButtonClickEvent = {

    Do {
       $Script:i++
       $Label.Text = $Script:i
       }
    Until ($Script:i = 10)    


}

$Button.Add_Click($ButtonClickEvent)


$MainForm.ShowDialog()
$MainForm.Dispose()

Is there a way, I can include a loop on such way, so that when I click once the button, it runs through the loop?

If I remove the loop and leave it as:

       $Script:i++
       $Label.Text = $Script:i

I can click through and the count starts and it runs but I would like to have a loop running within the Click for another purpose.

Upvotes: 0

Views: 1059

Answers (1)

Rich Moss
Rich Moss

Reputation: 2384

In Powershell assignment uses = and comparison uses -eq.

Change this line:

until ($Script:i = 10)

To this:

until ($Script:i -eq 10)

Upvotes: 3

Related Questions