Search code examples
windowsbatch-filecmdkeypress

How to get the y/n key press directly without using choice and set /p


I am trying to get y/n keypress without using choice and set /p. I have used del like this:

@echo off
copy /y nul $~temp.txt
del /p $~temp.txt >nul
if exist $~temp.txt (
  echo/
  echo You pressed y.
) else (
  echo/
  echo You pressed n.
)
pause >nul

It does not directly takes key press. We have to press enter key after that. Any method without pressing the enter key is appreciated.


Solution

  • You could (mis-)use xcopy, which prompts whether to continue copying when the /W option is specified; the /L switch prevents anything to be actually copied:

    @echo off
    rem // Capture first line of output of `xcopy /W`, which contains the pressed key:
    for /F "delims=" %%K in ('
        xcopy /W /L "%~f0" "%TEMP%"
    ') do set "KEY=%%K" & goto :NEXT
    :NEXT
    rem // Extract last character from captured line, which is the pressed key:
    set "KEY=%KEY:~-1%"
    rem // Return pressed key:
    echo You pressed "%KEY%".
    
    rem // Check pressed key (example):
    if /I not "%KEY%"=="Y" if /I not "%KEY%"=="N" >&2 echo You pressed an unexpected key!
    

    Alternatively, you could (mis-)use replace, which prompts whether to continue replacing when the /W option is specified; the /U switch prevents anything to be actually copied when source and destination are the same:

    @echo off
    rem // Capture second line of output of `replace /W`, which is the pressed key:
    for /F "skip=1 delims=" %%K in ('
        replace /W /U "%~f0" "."
    ') do set "KEY=%%K" & goto :NEXT
    :NEXT
    rem // Return pressed key:
    echo You pressed "%KEY%".
    
    rem // Check pressed key (example):
    if /I not "%KEY%"=="Y" if /I not "%KEY%"=="N" >&2 echo You pressed an unexpected key!
    

    I have to admit that I cannot remember whether or not replace was available on Windows XP though.