r/PowerShell • • Jun 25 '24

Simple counter

Hello

I have no idea what I am doing so my apologies. I want a simple counter that starts at 0 and if the + key is pressed then the counter goes up to 1 and it displays the value. If pressed again then it goes to 2 and displays that. Can anyone assist me please.

0 Upvotes

11 comments sorted by

View all comments

-1

u/AncientMoose6539 Jun 25 '24

Here is a snippet that does what you want but will also lead you to realize you need to refine your line of questioning:

$counter = 0

While($true){

    $keyPressed = $Host.UI.RawUI.ReadKey()

    if($keyPressed.VirtualKeyCode -eq 107){
        $counter += 1
        Write-Host "Key presses made: $counter"
    }
    else{
        #not the plus key, do nothing
    }
}

0

u/Netstaff Jun 26 '24

Your script does not respects those, who have no numpad, here, I enhanced it, and added some formatting with carriage return:

function Start-SimpleCounter {
    $counter = 0

    Write-Host "Press '+' to increment the counter. Press 'Esc' to exit."
    Write-Host "Current count:$counter" -NoNewline

    while ($true) {
        if ($Host.UI.RawUI.KeyAvailable) {
            $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
            
            if ($key.VirtualKeyCode -in 187, 107) {  # '+' key (main or numpad)
                $counter++                
                Write-Host "`rCurrent count:$counter" -NoNewline #write and return carriage.
            }
            elseif ($key.VirtualKeyCode -eq 27) {  # 'Esc' key
                Write-Host "`nExiting..."
                break
            }
        }
    }
}

# To run the function, simply call:
Start-SimpleCounter

1

u/AncientMoose6539 Jun 26 '24

Meh, I did something quick and dirty that I knew wouldn't work for whatever larger task this section was supposed to plug into and I make no apologies for that. OP needed to provide better questioning and trying to plug in my half-assed code was intended to help him realize that.