使用Powershell在BAT中input默认的可编辑string

我正在试图在BAT脚本中获得可编辑的input,类似于在bash中读取-i。

我看到了各种解决方法,但是我发现它们太复杂或太长,或者依赖于其他文件/非本地资源。

有没有什么办法可以在bat中使用powershell来模仿可编辑默认string的input?

我发现这可以从蝙蝠内部调用:

powershell -Command "$input = read-host 'Enter Input: '" 

 set /p INPUTSTRING=Enter Input: 

请注意,这不会让您编辑预先存在的变量。 要做到这一点需要一个不同的程序。 我自己的程序editv32.exe / editv64.exe可以让你这样做:

 set INPUTSTRING=Test string editv32 -p "Enter input: " INPUTSTRING 

这将在INPUTSTRING变量的现有内容之后显示“Enter input:”提示,您可以编辑它。

下载在这里: http : //www.westmesatech.com/editv.html

无限制版权的免费软件。

下面的解决方案是一个Batch-JScript混合脚本,它使用SendKeys来填充命令行输入缓冲区的默认值,因此用户可以在执行set /P命令时使用标准编辑键对其进行编辑。 但是这种方法的缺点是缓冲区的填充总是出现在屏幕上,所以在用户输入数据之前必须清除。 我正在努力解决这一点。

编辑 :在读取MC ND的答案后,我意识到,没有必要在实际输入之前预先填写输入缓冲区,因为刚刚输入的字符也可以以相同的方式编辑; 这一点导致了一个更简单的解决方案。

下面的方法只是用一个可编辑的字符串预填充输入 ; 它不会尝试以任何方式修改原始的set /P命令行为。

 @if (@CodeSection == @Batch) @then @echo off rem Enter the prefill value CScript //nologo //E:JScript "%~F0" "Prefill value" rem Read the variable set /P "var=Prompt: " echo var=%var% goto :EOF @end WScript.CreateObject("WScript.Shell").SendKeys(WScript.Arguments(0)); 

有关更多详细信息,请参阅此帖子 。

遵循Aacini最初的想法。 我没有在所有可能的情况下测试它,但似乎工作。

EDITED – 更新代码以在编辑行时检测Ctrl + C键。 调用子程序返回错误级别来发信号。

 @if (@this == @isBatch) @then @echo off setlocal enableextensions call :prefilledSet/P data "Edit this:" "This is the data that must be edited" if not errorlevel 1 ( echo(Data retrieved: [%data%] ) else ( echo( echo( ---- Input has been canceled ) endlocal exit /B :prefilledSet/P variable "Prompt" "Prefill value" setlocal enableextensions disabledelayedexpansion set "line=" <nul set /p "v=%~2" for /f "delims=" %%a in ('cscript //nologo //e:jscript "%~f0" "%~3"' ) do if not defined line ( set "line=%%a" & set "exitCode=0" ) else if "%%a"=="ERROR" ( set "line=" & set "exitCode=1" ) endlocal & set "%~1=%line%" & exit /b %exitCode% @end WScript.CreateObject("WScript.Shell").SendKeys(WScript.Arguments(0)); try { WScript.StdOut.WriteLine( WScript.StdIn.ReadLine() ); } catch (e) { WScript.StdOut.WriteLine('ERROR\r\nERROR'); WScript.Quit(1) }; 

编辑 – 只是添加另一个选项。 但抱歉,不能直接批量编码。 如果你有选择编译一个简单的工具(用mingw gcc编译器测试),这个c代码

 #define _WIN32_WINNT 0x0500 #include "windows.h" int main(int argc, char **argv){ HWND hWnd = NULL; int i; if (argc < 2) return 1 ; hWnd = GetConsoleWindow(); for (i=0;i<strlen(argv[1]);i++){ PostMessage(hWnd, WM_CHAR, argv[1][i], 0); }; return 0; } 

编译时会生成一个命令行工具,它将把作为第一个参数给出的文本发送到当前控制台。 所以,它可以用作(例如编译为typetext.exe)

 typetext.exe "this is the text to edit" & set /p "var=edit this text:" 

由于文本直接发送到工具所在的控制台,因此执行时不会干扰其他窗口处于活动状态。

另一种选择是ReadLine.exe:

 @echo off set NAME=First Last for /f "delims=" %%n in ('ReadLine -p "Enter name: " -- %NAME%') do set NAME=%%n echo You entered: %NAME% 

你可以从http://www.westmesatech.com/misctools.html得到它&#x3002; 包括源代码。