Page 1 of 1

Closing a PowerShell window with other keys [SOLVED]

Posted: 2023-Aug-31, 4:47 pm
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?

Re: Closing a PowerShell window with other keys

Posted: 2023-Aug-31, 6:41 pm
by Simon Sheppard
You could probably modify this function (function Test-KeyPress) to get that behaviour:

https://powershell.one/tricks/input-dev ... -key-press

Re: Closing a PowerShell window with other keys

Posted: 2023-Aug-31, 11:23 pm
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