forms - Anonymous clickhandler in foreach loop uses last variable state -
i guess newbie question. yet did not find online...
i'm creating small powershell script simple gui.
this relevant part of script:
foreach ($script in $scripts){ $btn = new-object system.windows.forms.button #text, location, size omitted #add clickhandler $btn.add_click( { write-host "clicked on btn $script" start-process -filepath "powershell" -argumentlist "-command", "`"$script`"" write-host "finished" $form.close(); } ) $form.controls.add($btn) }
obviously $scripts
contains paths pointing towards other powershell scripts. being java developer naiv enough suspect every click handler created own reference script location ($script
).
but of course powershell not evaluate $script
until handler invoked. thus, every button call last element in array $scripts
since $script
reference last element in $scripts
after loop completes.
how can create click handler inside foreach
-loop based on loop-variable itself?
solution
mathias r. jessen pointed me working solution. .getnewclosure()
called on handler worked.
working code:
foreach ($script in $scripts){ $btn = new-object system.windows.forms.button #text, location, size omitted #add clickhandler $btn.add_click( { write-host "clicked on btn $script" start-process -filepath "powershell" -argumentlist "-command", "`"$script`"" write-host "finished" $form.close(); }.getnewclosure() ) $form.controls.add($btn) }
solution
mathias r. jessen pointed me working solution. .getnewclosure() called on handler worked.
working code:
foreach ($script in $scripts){ $btn = new-object system.windows.forms.button #text, location, size omitted #add clickhandler $btn.add_click( { write-host "clicked on btn $script" start-process -filepath "powershell" -argumentlist "-command", "`"$script`"" write-host "finished" $form.close(); }.getnewclosure() ) $form.controls.add($btn) }
Comments
Post a Comment