batch file to mask input with * without an externa

2019-01-27 09:17发布

问题:

i need batch file to mask the input with * without external file and i need the code to be fast to write letters

FOR EXAMPLE:

     @echo off
     set char=*
     set /p variable=Enter your password:
     set char=%variable%
     echo %char%
     pause

回答1:

Here is a way to do it using Powershell in a batch file

@echo off
set "psCommand=powershell -Command "$pword = read-host 'Enter Password' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
echo %password%

Powershell is installed by default on all newer OS's so it's a good compromise. If you have to support XP machines, you can do something similar with VBScript.



回答2:

Yes! There is a way in pure batch, with misusing of xcopy and prompt command we can do it

    @echo off
setlocal enabledelayedexpansion
call:show "Enter your passwordÿ" "0a"
call:hidePass
set /p password=<_tmp&del _tmp&echo/
echo/%password%
pause>nul
exit
:hidePass
    set "str="
    set "chars="
:writing
    set "key="
    for /F "usebackq delims=" %%L in (`xcopy /L /w "%~f0" "%~f0" 2^>NUL`) do (
        if not defined key set "key=%%L"
    )
    setlocal EnableDelayedExpansion
    set "key=!key:~-1!"
    if "%key%" == "" (echo/!str!>_tmp&exit/b)
    call:show "-" "0c"
    set "str=!str!!key!"
    goto :writing
:show
    for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
        set "DEL=%%a"
    )
    call :ColorText %~2 "%~1"
    exit/b
:ColorText
    <nul set /p ".=%DEL%" > "%~2"
    findstr /v /a:%1 /R "^$" "%~2" nul
    del "%~2" > nul 2>&1
    exit/b

The only problem is you can not use * as mask, in this case I'm using -