Powershell button to run each time it's clicked

Tag: powershell Author: zjubmehuning Date: 2014-02-06

Im trying to get a password button to generate a new password each time the button is clicked. The first click generates a password with my requirements just fine, but i need it to re-run on each click. I know its probably something simple within the add_click(), but i can't seem to find anything. Below is everything i have pertaining to the button and the password generation.

#form1: Button1 "password generate" 
$button1 = New-Object system.windows.forms.button
$button1.location = "10, 25"
$button1.size = "125, 35"
$button1.text = "Generate Password"
$button1.add_click($displayPassword)
$form1.controls.add($button1)

#######Password######

$caps = [char[]] "ABCDEFGHJKMNPQRSTUVWXY"
$lows = [char[]] "abcdefghjkmnpqrstuvwxy"
$nums = [char[]] "2346789"
$special = [char[]] "#%$+<=>?"

$first = Get-Random -Minimum 2 
$second = Get-Random -Minimum 2
$third = Get-Random -Miniumum 2 
$fourth = Get-Random -Minimum 2
$ofs = ""
$pwd = [string](@($caps | Get-Random -Count $first) + @($lows | Get-Random -Count $second) + @($nums | Get-Random -Count $third)+ @($special | Get-Random -Count $fourth) | Get-Random -Count 15)

$displayPassword = {$textbox1.text = "$pwd"}

Best Answer

Everything used to calculate the random password runs only one time. Your click eventhandler only updates the textbox, but it never regenerates a new password.

Try something like this:

#form1: Button1 "password generate" 
$button1 = New-Object system.windows.forms.button
$button1.location = "10, 25"
$button1.size = "125, 35"
$button1.text = "Generate Password"
$button1.add_click({
    $first = Get-Random -Minimum 2 
    $second = Get-Random -Minimum 2
    $third = Get-Random -Miniumum 2 
    $fourth = Get-Random -Minimum 2
    $pwd = [string](@($caps | Get-Random -Count $first) + @($lows | Get-Random -Count $second) + @($nums | Get-Random -Count $third)+ @($special | Get-Random -Count $fourth) | Get-Random -Count 15)
    $textbox1.text = "$pwd"

})

$form1.controls.add($button1)

#######Static Password Resources######

$caps = [char[]] "ABCDEFGHJKMNPQRSTUVWXY"
$lows = [char[]] "abcdefghjkmnpqrstuvwxy"
$nums = [char[]] "2346789"
$special = [char[]] "#%$+<=>?"
$ofs = ""

FYI, for future questions, include a complete and working sample. Your sample references $form1 and $textbox1 which are never declared.

comments:

That, and $displayPassword must be defined before it's added to the button.
+1 True. Fixed. :)
Thanks @FrodeF. That fixed my issue. Makes sense now that you explained it. Im still learning, started powershell yesterday. Any idea why that even though i set minimums, they don't always have the minimum?