2014-02-22 363 views
0

我試圖獲得一個密碼按鈕,每次單擊按鈕時都會生成一個新密碼。第一次點擊生成的密碼與我的要求很好,但我需要它重新運行每次點擊。我知道它在add_click()內可能很簡單,但我似乎無法找到任何東西。以下是我有關按鈕和密碼生成的一切。Powershell按鈕每次點擊時運行

#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"} 

回答

3

用來計算隨機密碼的所有東西只運行一次。您的點擊事件處理程序僅更新文本框,但不會重新生成新密碼。

嘗試這樣:

#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 = "" 

僅供參考,爲未來的問題,包括一個完整的,工作樣本。您的樣本參考文獻$form1$textbox1從未聲明。

+1

在添加到按鈕之前,必須先定義'$ displayPassword'。 –

+0

+1正確。固定。 :) –

+0

謝謝@FrodeF。這解決了我的問題。現在你解釋它是有意義的。我還在學習,昨天開始了PowerShell。任何想法爲什麼即使我設置最低限度,他們並不總是有最低限度? – user3341736