Escape user input in windows batch file

前端 未结 1 1491
执笔经年
执笔经年 2021-01-13 04:53

I have a windows batch file that accepts a password as user input:

SET /P PASSWORD=Password:

This password might have characters that need

1条回答
  •  离开以前
    2021-01-13 05:16

    It's a nice challenge, but this is advanced batch technic.
    I would use here a simpler way, use delayed expansion and do not send the content, only the variable name.

    This is absolute safe even with special characters.

    call foo.bat password
    

    Foo.bat -----------------

    Setlocal EnableDelayedExpansion
    Echo !password!
    

    EDIT: Solution for the original question,
    this is a way to solve it with the content instead of an variable name

    It's necessary to prepare the content before sending it via CALL to second batch file.
    It's hard to use something like CALL foo.bat %preparedVariable%
    It's seems to be better to use CALL foo.bat !preparedVariable!
    But even then I fail at the doubling of carets by the CALL-phase.

    But then I found a simple way to use the percent expansion just after the CALL-phase.

    @echo off
    
    setlocal DisableDelayedExpansion
    rem set /p "complex=Complex Input "
    set "complex=xx! & "!^&"ab^^ " ^^^^cd%%"
    
    setlocal EnableDelayedExpansion
    
    call :prepareForCallBatch complex PreparedParam
    echo Send   =!PreparedParam!#
    set complex
    echo(
    call ShowParam.bat %%PreparedParam%%
    exit /b
    
    :: Prepare special characters &|<>"^ for a batch call
    :prepareForCallBatch
    set "temp=!%~1!"
    
    set "temp=!temp:^=^^!"
    set "temp=!temp:&=^&!"
    set "temp=!temp:|=^|!"
    set "temp=!temp:<=^=^>!"
    set "temp=!temp:"=^^"!"
    set "%~2=!temp!"
    exit /b
    

    To see the real parameters in ShowParam.bat I use something like this
    ShowParam.bat

    @echo off
    setlocal
    set prompt=
    @echo on
    REM # %* #
    

    0 讨论(0)
提交回复
热议问题