Reputation: 47
I'm trying to create 8 labels, and edit the .Text property of them.
I've been searching for a while, but have not been able to find anything online. Though, I could be searching this out incorrectly.
Here's an example of what I'm trying to do:
for ($i=1; $i -le 8; $i++)
{
New-Object -TypeName System.Windows.Forms.Label | New-Variable -name "testing$i"
$testing$($i).Text = 'text of label'
}
I feel like I'm pretty close, but I've run out of ideas. I wondered if someone may have a resource, or suggestion.
Thanks!
Upvotes: 2
Views: 63
Reputation: 437062
TessellatingHeckler's answer shows you an alternative approach that doesn't require declaring individual variables (one for each label), which is generally preferable.
If you do want label-individual variables, after all:
for ($i=1; $i -le 8; $i++)
{
New-Object -TypeName System.Windows.Forms.Label | New-Variable -name testing$i
Set-Variable -Name testing$i -Value 'text of label'
}
Just like you used the New-Variable
cmdlet to create a variable by a dynamically constructed name, you need Set-Variable
to set it (assign to it).
As the LHS of an assignment, a $
-prefixed token must be followed by a literal variable name, which is why $testing$($i)
failed.
Upvotes: 1
Reputation: 28963
Use a collection
$labels = 1..8 | foreach-object { New-Object -TypeName System.Windows.Forms.Label }
$labels | foreach-object { $_.Text = 'text of label' }
Upvotes: 1