简体   繁体   English

减少 PowerShell 脚本中的重复命令

[英]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.您可以看到这 3 行重复仅在两个位置更改414243等。

How can I make it look better?我怎样才能让它看起来更好? it looks so bad.它看起来很糟糕。

you can do this with a loop:你可以用一个循环来做到这一点:

In order to test it, I created 3 folders in C:\\ (1Test1-Kopie,2Test2-Kopie,3Test3-Kopie)为了测试它,我在 C:\\ (1Test1-Kopie,2Test2-Kopie,3Test3-Kopie) 中创建了 3 个文件夹

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对于你的代码,我用 ...4${Z} 替换了 41,42 和 43...因为只有最后一位数字在改变...试着找出它是否有效

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}})}
$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.不确定 powershell 中文本框上的“名称”属性的名称,因此在拉取子字符串时可能需要更改为对象的实际名称属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM