Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read individual key presses (integers) in PowerShell

Tags:

powershell

I am aware of this question but it doesn't answer my current question.

I know that the current line gives me the next pressed key:

$Host.UI.RawUI.ReadKey().Character

For example, if I press 1, I get 1.

But that is a string (well, actually a char), I want the number as an integer.

I try with:

[int]$Host.UI.RawUI.ReadKey().Character

And:

$Host.UI.RawUI.ReadKey().Virtualkeycode

But in both lines, if you press 1, you instead get 49.

I know that I can simply do:

[int]$Host.UI.RawUI.ReadKey().Character - 48

But I was wondering if there is any better way to do that. For example, if I want to get both letters and numbers, the usage of -48 would make a bit more difficult, since I would need to use some conditional blocks.

So, my question is: Is there any better way to get the pressed key (number) as integer rather than [int]$Host.UI.RawUI.ReadKey().Character - 48?

like image 522
Ender Look Avatar asked Jan 01 '23 06:01

Ender Look


1 Answers

An option you have is the System.Int32.Parse method:

PS> [int]::Parse

OverloadDefinitions
-------------------
static int Parse(string s)

In use:

$in = $Host.UI.RawUI.ReadKey().Character
[int]::Parse($in)

You can also use System.Int32.TryParse if you think the user will enter something non-integer:

PS> [int]::TryParse

OverloadDefinitions
-------------------
static bool TryParse(string s, [ref] int result)

In use:

[int] $out = 0
$in = $Host.UI.RawUI.ReadKey().Character
if ([int]::TryParse($in, [ref]$out)) {
    $out
}
else {
    Write-Warning 'Non-int entered!'
}
like image 150
Maximilian Burszley Avatar answered Jan 13 '23 13:01

Maximilian Burszley