readline-sync/lib/read.bat

43 lines
1.2 KiB
Batchfile
Raw Normal View History

@echo off
setlocal
2015-03-03 18:30:41 +01:00
setlocal ENABLEDELAYEDEXPANSION
2015-03-07 11:59:01 +01:00
if "%~1"=="noechoback" (
2015-03-05 09:39:46 +01:00
call :read_s
2015-03-03 18:30:41 +01:00
if ERRORLEVEL 1 exit /b 1
2014-07-12 00:37:25 +02:00
) else (
2015-03-01 07:06:53 +01:00
set /p INPUT=<CON >CON
2014-07-12 00:37:25 +02:00
)
2015-03-01 07:06:53 +01:00
set /p ="'%INPUT%'"<NUL
endlocal
exit /b 0
2015-03-05 09:39:46 +01:00
:: Silent Read
:read_s
:: where /q powershell
2015-03-03 18:30:41 +01:00
:: Win <Vista and <Server2008 don't have `where`.
powershell /? >NUL 2>&1
:: Win <7 and <Server2008R2 don't have PowerShell as default.
:: Win XP and Server2003 have `ScriptPW` (`scriptpw.dll`).
:: In the systems that don't have both, an error is thrown.
2015-03-03 18:30:41 +01:00
if ERRORLEVEL 1 (
set "EXECOMMAND=cscript //nologo "%~dp0read.cs.js""
) else (
2015-03-03 18:30:41 +01:00
set "EXECOMMAND=powershell -Command "$text = read-host -AsSecureString; ^
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR^($text^); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto^($BSTR^)""
)
2015-03-03 18:30:41 +01:00
:: Can't get `ERRORLEVEL` from sub-shell (`for`).
:: 2 `%ERRCODE%` lines are returned if an error is thrown.
set ERRCODE=ERR
set "EXECOMMAND=%EXECOMMAND% ^& if ERRORLEVEL 1 ^(echo %ERRCODE%^& echo %ERRCODE%^)"
:: echo %EXECOMMAND%
for /f "usebackq delims=" %%i in (`%EXECOMMAND%`) do (
if "%%i"=="%ERRCODE%" if "!INPUT!"=="%ERRCODE%" exit /b 1
set "INPUT=%%i"
)
exit /b 0