Dynamically Updating a GUI Control with PowerShell

Using our previous basic form as a starting point, how would we go about updating the label to show some useful data which may update frequently?

To keep the example short, we can have the label update with a random number every second and change the colour based on whether it is odd or even.

Firstly, we need to create a function which takes our Label control as an input and updates the Text value.

function GetRandomNumber($Label) {

    $Number = Get-Random -Minimum 1 -Maximum 100
    $Label.Text = "The random number is ($Number)"

    if (($Number % 2) -eq 0) {
        $Label.ForeColor = "Green"
    }
    else {
        $Label.ForeColor = "Red"
    }
}

We then need to create a Timer object that calls the above function at regular intervals. This code would be added before we called $Form.ShowDialog()

$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 2000
$Timer.Add_Tick( {GetRandomNumber $Label})
$Timer.Enabled = $True

That’s it, once we show the form the function will run every 2 seconds the value and colour of the label should update.