Closing a PowerShell window with other keys [SOLVED]

Microsoft Windows
Post Reply
SS##66
Posts: 28
Joined: 2023-Jan-24, 4:51 pm

Closing a PowerShell window with other keys [SOLVED]

Post by SS##66 »

I have this script - but it only closes the PS window when I press Enter [thus ignoring addition of being able to use also Space and Esc]:

Code: Select all

Write-Host "To close this window press either:"
Write-Host " Enter"
Write-Host " Space"
Write-Host " Esc"

do {

    $key = $Host.UI.RawUI.ReadKey('NoEcho, IncludeKeyDown').Character

} while ($key -notin @(

    [char]13,   # Enter
    ' ',   # Space
    [char]27   # Escape [carriage return]

    )
)

Read-Host
How can this be fixed?
Last edited by SS##66 on 2023-Aug-31, 11:23 pm, edited 2 times in total.
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: Closing a PowerShell window with other keys

Post by Simon Sheppard »

You could probably modify this function (function Test-KeyPress) to get that behaviour:

https://powershell.one/tricks/input-dev ... -key-press
SS##66
Posts: 28
Joined: 2023-Jan-24, 4:51 pm

Re: Closing a PowerShell window with other keys

Post by SS##66 »

This seem to be working A-OK

Code: Select all

Write-Host "To close this window press either:"
Write-Host " Enter"
Write-Host " Space"
Write-Host " Esc"

function Wait_For_Pressing_Of_A_Specified_Key
    {
    
    do
        {
        $keyInfo = [Console]::ReadKey($true)
        }
    
        while ($keyInfo.Key -notin
            @(
            [ConsoleKey]::Enter,
            [ConsoleKey]::Escape
            [ConsoleKey]::Spacebar
            ))
    }

Wait_For_Pressing_Of_A_Specified_Key
So thank you for pointing me in the right direction
Post Reply