0

The only ways I know to check if a key is pressed in Powershell are $Host.UI.RawUI.ReadKey() and [console]::ReadKey(). I want to make a script that writes in the console "1 is pressed" whenever 1 is pressed and"1 ain't pressed" whenever 1 isn't pressed. However, I am having trouble with how both of these will not give the "1 ain't pressed" output unless a non-1 key is pressed. Is there a way to check if 1 is not pressed without having to press a non-1 key? Here are the scripts I tested:

#Using $Host.UI.RawUI.ReadKey()
for(;;){
$key = $Host.UI.RawUI.ReadKey()
if($key.Character -eq '1'){
Write-Output "1 is pressed"}
else{
Write-Output "1 ain't pressed"}}
#Using [console]::ReadKey()
for(;;){
$key = [console]::ReadKey()
if ($key.Key -eq 'D1') {
Write-Output "1 is pressed"}
else{
Write-Output "1 ain't pressed"}}
mklement0
  • 382,024
  • 64
  • 607
  • 775
PlatoHero
  • 31
  • 5
  • I would like to clarify that this is a yes or no question, but if the answer to the question is yes, further clarification as to why that is would be greatly appreciated. – PlatoHero Jun 22 '22 at 17:46
  • A possible reason for why your question received little attention is that you tagged it only as `powershell-5.1` and not also as `powershell` (I've just done the latter). Apart from that, the code you've posted seems to work as intended, so it's unclear what problem you're facing. – mklement0 Jul 03 '22 at 22:00

0 Answers0