PowerShell计数器没有递增

时间:2017-01-03 14:10:42

标签: powershell counter

我正在尝试创建一个小型的PowerShell程序,它会向您询问一个随机单词并且您必须翻译它。我使用两个数组的索引来确定答案是否正确。

每次用户输入正确或错误的答案时,文本框都应增加其值,以显示用户到目前为止有多少是非。该程序到目前为止应用,但计数器不是。此时计数器仅增加到1并且不会超过1.我错过了什么?

我认为问题可能是PowerShell总是调用来自外部反正确和反错误的值,但是我怎么能解决它只调用递增的值?

$QuestionArray = New-Object System.Collections.ArrayList
$AnswerArray = New-Object System.Collections.ArrayList
$countercorrect = 0
$counterwrong = 0

#word array
$QuestionArray.Add("word1")
$QuestionArray.Add("word2")
$QuestionArray.Add("word3")

#solution array
$AnswerArray.Add("answer1")
$AnswerArray.Add("answer2")
$AnswerArray.Add("answer3")

#Function to display a new word
function Question {
    $global:RandomQuestion = $QuestionArray | Get-Random
    $SearchedTextbox.Text = $global:RandomQuestion
}

$InputTextbox.Add_KeyDown({
    if ($_.KeyCode -eq "Enter") {
        #Get User Guess
        $Answer = $InputTextbox.Text
        #Get Solution array Index
        $IndexPositionQuestion = [array]::indexof($QuestionArray, $global:RandomQuestion)
        #Get User answer array Index
        $IndexPositionAnswer = [array]::indexof($AnswerArray, $Answer)
        #Check if both indexes match
        If($IndexPositionAnswer -eq $IndexPositionQuestion){

            #this fails / doesn't go above 1
            $RightTextBox.Text = countercorrect++
            Question
        }else{

            #this fails / doesn't go above 1
            $WrongtTextBox.Text = counterwrong++ 
            Question
        }
    }
})

我尝试使用单独的函数来增加其值,但即使只增加到1。

1 个答案:

答案 0 :(得分:2)

简化示例:

$form = New-Object System.Windows.Forms.Form

$counter = 0

$button = New-Object System.Windows.Forms.Button
$button.Text = "button"
$button.Add_Click({

    $script:counter++

})

$form.Controls.Add($button)

$form.ShowDialog()

$counter

如果您将$script:counter++替换为$counter++,则该值不会正确递增。

相关问题