Simple increment/decrement counter

ScriptingBerry picture ScriptingBerry · Apr 5, 2013 · Viewed 16.4k times · Source

I would like to make a simple counter in PowerShell. It must prompt the user whether they'd like a higher or lower number.

The starting number must be 0, and it can't be lower than zero or higher than 10. If the user wants a higher number, it must increment the number with 1, if lower decrement by 1. Then it must be able to stop at the desired number. With this number I can set a registry value.

I don't know an efficient way to prompt the user. I can use the Read-Host cmdlet to ask if they typed "higher" or "lower", but is there a more efficient way to accomplish this?

For example,

$i = 0

while (($i -gt 0) -or ($i -lt 10)){
    $j = Read-Host "The current number is $i, would you like a higher/lower number, or quit?"

    if ($j -eq "higher") {
        $i++
        Write-Host "The current number is $i"
    } elseif ($j -eq "lower") {
        $i--
        Write-Host "The current number is $i"
    } elseif ($j -eq "quit") {
        Write-Host "Final number is: $i"
        break
    }
}

How can I do this?

Answer

Richard picture Richard · Apr 5, 2013

You could use the Yes/No Prompt Window to get user input.

$a = new-object -comobject wscript.shell
$intAnswer = $a.popup("Do you want to delete these files?", 0, "Delete Files", 4)
If ($intAnswer -eq 6) {
    $a.popup("You answered yes.")
}
else {
    $a.popup("You answered no.")
}

If you replace the '3' in the fourth parameter of the popup() function you will get Yes, No, and Cancel buttons in the prompt window.

Reference: Provide a Yes/No Prompt in Windows PowerShell