如何避免变量中的任何符号

时间:2015-09-09 19:06:34

标签: batch-file

我创建了一个批处理文件,如下所示

@echo off
setlocal EnableDelayedExpansion
echo  Type Below Requirements:
echo.
:username
set /p usr= Type Username:
if [!usr!]==[] goto username
:password
set /p pwd= Type Password:
if [!pwd!]==[] goto password
echo.
echo Your username is: !usr!
echo Your password is: !pwd!

它工作正常,但我想避免使用任何符号或空格(例如:@ @ $%^& *)来输入用户名。

可能,请建议。

1 个答案:

答案 0 :(得分:0)

您可以使用for /f循环在所有字母数字字符上拆分用户名。然后,如果剩下任何东西,它可能无效。

:username
set /p "usr=Username: "
if not defined usr goto username
for /f "delims=abcdefghijklmnopqrstuvwxyz0123456789" %%I in ("!usr!") do (
    echo Username must not contain any non-alphanumeric characters.
    goto username
)

要获得额外的功劳,您可以使用PowerShell对控制台中的密码输入进行模糊处理。这是一个完整的例子:

@echo off
setlocal EnableDelayedExpansion
echo  Type Below Requirements:
echo.
:username
set /p "usr=Username: "
if not defined usr goto username
for /f "delims=abcdefghijklmnopqrstuvwxyz0123456789" %%I in ("!usr!") do (
    echo Username must not contain any non-alphanumeric characters.
    goto username
)

set "psCommand=powershell -noprofile "$p=read-host -AsSecureString;^
$m=[System.Runtime.InteropServices.Marshal];$m::PtrToStringAuto($m::SecureStringToBSTR($p))""

:password
<NUL set /P "=Password: "
for /f "usebackq delims=" %%I in (`%psCommand%`) do set "pwd=%%I"
if not defined pwd goto password

echo.
echo Your username is: !usr!
echo Your password is: !pwd!