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

18

u/MNmetalhead Jun 25 '24

Do you have any code that you tried already that you can share? That will give us something to help you with instead of just doing it for you.

14

u/root-node Jun 25 '24

If posting a question in Script Help, include all relevant information about the environment and the whole script you are working on.

What have you done so far?

7

u/ka-splam Jun 25 '24

Run calc.exe for Windows Calculator, press +1 and then Enter and it goes to 1 and displays the value. Press enter again and it goes to 2 and displays that. The more you press enter, the higher it counts.

3

u/Respond-Creative Jun 25 '24

But run it from the PS command window ;) #poshftw

-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.

-4

u/CloudStrifeDota Jun 25 '24

Thank you good sir

-1

u/g3n3 Jun 25 '24

You realize how presumptuous and rude it is to post in this manner?

0

u/[deleted] Jun 25 '24

[deleted]

-3

u/CloudStrifeDota Jun 25 '24

Thank you very much