Shahar
Shahar

Reputation: 501

Reduce repetitive commands in PowerShell script

Im really embarrassed asking this, but I have a script which I'm trying to make it look better, and less repetetive.

It has the following lines:

$textbox41.Add_Click({if ($Box41Trigger){$textbox41.text = ""; $textbox41.ForeColor="black";$script:Box41trigger=$false}})
$textbox42.Add_Click({if ($Box42Trigger){$textbox42.text = ""; $textbox42.ForeColor="black";$script:Box42trigger=$false}})
$textbox43.Add_Click({if ($Box43Trigger){$textbox43.text = ""; $textbox43.ForeColor="black";$script:Box43trigger=$false}})

You can see those 3 lines are repetitive only changing 41, 42, 43 etc. in two locations.

How can I make it look better? it looks so bad.

Upvotes: 0

Views: 64

Answers (2)

Andrew Ryan Davis
Andrew Ryan Davis

Reputation: 659

$textBoxList = @(
    $textBox41,
    $textBox42,
    $textBox43
)

foreach ($textBox in $texBoxList) {
    $textBoxTrigger = 'box' + $textBox.Name.Substring($textbox.length -2) + 'Trigger'
    $textBox.Add_Click( {
        if ($textBoxTrigger) { 
            $textBox.text = ""; 
            $textBox.ForeColor="black"; 
            $script:textBoxTrigger=$false
        }
    })
}

Another option for grabbing the number on that second variable. Not certain on the name of the "Name" property on a textbox in powershell, so that may need to change to whatever the objects actual name property is when pulling the substring.

Upvotes: 1

Adis1102
Adis1102

Reputation: 212

you can do this with a loop:

In order to test it, I created 3 folders in C:\ (1Test1-Kopie,2Test2-Kopie,3Test3-Kopie)

for ($Z=1; $Z -le 3; $Z++) 

{Get-item -Path "C:\${Z}Test${Z} - Kopie"} 

For your code i replaced 41,42 and 43 with ...4${Z}...as only the last digit is changing...try around to figure out if it works

for ($Z=1; $Z -le 3; $Z++) 

{$textbox4${Z}.Add_Click({if ($Box4${Z}Trigger){$textbox4${Z}.text = ""; $textbox4${Z}.ForeColor="black";$script:Box4${Z}trigger=$false}})}

Upvotes: 2

Related Questions