批量设置命令后回显文本

时间:2015-11-07 21:53:22

标签: batch-file cmd

有没有办法在设置命令后回显文本?我试过了,但似乎没什么用。这是我的代码:

@echo off
Echo Enter a website:
Set /p op="Https:\\"     ".com"
:: The ".com" would be displayed behind the users input.
if %op%==%op% goto Show
:Show
cls
Echo Website: Http:\\%op%.com
pause
exit

如何在输入后显示.com?无论用户输入多大,我都希望将“.com”冻结在一个位置。

2 个答案:

答案 0 :(得分:3)

我从this answer获取了解决方案并略微修改了它以满足此请求。

@echo off
setlocal EnableDelayedExpansion

for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a"

set "op="
set /P "=Https:\\.com!BS!!BS!!BS!!BS!" < NUL
:nextKey
   set "key="
   for /F "delims=" %%K in ('xcopy /W "%~F0" "%~F0" 2^>NUL') do if not defined key set "key=%%K" & set "key=!key:~-1!"
   if "!key!" equ "!CR!" goto endInput
   if "!key!" neq "!BS!" (
      set "op=%op%%key%"
      set /P "=.!BS!%key%.com!BS!!BS!!BS!!BS!" < NUL
   ) else if defined op (
      set "op=%op:~0,-1%"
      set /P "=.!BS!!BS!.com !BS!!BS!!BS!!BS!!BS!" < NUL
   )
goto nextKey
:endInput
echo/
echo/
echo Website: Http:\\%op%.com

编辑添加了新方法(在评论中提出要求)

@echo off
setlocal EnableDelayedExpansion

set /A spaces=10, backSpaces=spaces+4

set "spcs="
for /L %%i in (1,1,%spaces%) do set "spcs=!spcs! "
set "back="
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"
for /L %%i in (1,1,%backSpaces%) do set "back=!back!!BS!"

set /P "op=Https:\\%spcs%.com!back!"
echo/
echo Website: Http:\\%op%.com

答案 1 :(得分:0)

Per @ Marged的评论,我怀疑批处理文件不可能(或至少非常困难)。

这是一个有用的PowerShell解决方案:

function Get-UserInput {
    param (
        [parameter(mandatory = $false)]
        [string]$pre='Enter text:'
        ,
        [parameter(mandatory = $false)]
        [string]$post='_'
    )
    process {
        [string]$text=''
        while ($key.Key -ne 'Enter') {
            write-host "`r$pre$text$post " -NoNewline #trailing space to hide deleted chars
            #replace the above with the 3 below if you want user input to be a different colour to the defaults 
            #write-host "`r$pre" -NoNewline
            #write-host $text -NoNewline -ForegroundColor Cyan
            #write-host "$post " -NoNewline #trailing space to hide deleted chars

            $key = [Console]::ReadKey($true)
            switch ($key.Key)
            {
                'Backspace' { $text = $text.substring(0,($text.length-1)) }
                default { $text = $text + $key.KeyChar }
            }
        }
        write-host "" #undo no new line
        write-output "$pre$text$post" 
    }
}

clear-host
$input = Get-UserInput -pre 'https://' -post '.com'
"User entered: '$input'"