【问题标题】:How to pass run time argument to start exe from batch file如何传递运行时参数以从批处理文件启动 exe
【发布时间】:2019-10-07 10:14:07
【问题描述】:

我创建了一个接受用户输入的批处理文件,然后它启动了一个exe 文件,并将用户输入作为其运行时参数。

@echo off

set /p version= "Please enter the version   "
ECHO version is %version%

cd %USERPROFILE%\Documents
START demo.exe -v %version%

使用上面的代码,它根本不会启动 exe。如果我将START 命令替换为以下内容:

START demo.exe -v 2019.1.133

然后重新运行批处理文件,它会启动 exe。谁能告诉我这里的错误是什么。

谢谢

【问题讨论】:

    标签: batch-file exe flags


    【解决方案1】:

    使用提供的代码无法在没有输入版本字符串的情况下启动 demo.exe。仅当发布的代码位于以( 开头并以匹配) 结尾的命令块内时,才会发生这种情况。在这种情况下,需要delayed expansion,如在命令提示符窗口set /? 中运行时命令SET 输出的帮助所述。 Windows 命令处理器cmd.exe 在使用该命令块执行命令(通常是IFFOR)之前解析整个命令块。在解析命令块期间,整个命令块中的每个 %variable% 引用都被引用的环境变量的当前值替换,如 How does the Windows Command Interpreter (CMD.EXE) parse scripts? 所述,并且可以在 debugging a batch file 中看到。对于在解析命令块期间未定义的环境变量,最终执行的命令行不包含任何内容,而不是 %variable%

    让我们假设代码不在命令块内,这通常是可能的,因为命令 GOTO 可以在以冒号开头的行下方继续执行批处理文件,因此使用的设计至少在 IF 条件下避免使用命令块。

    这里是提供的代码的改进版本:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    
    rem Delete environment variable Version before each user prompt. The
    rem user is prompted until a valid version string is input by the user.
    :EnterVersion
    set "Version="
    set /P Version="Please enter the version: "
    
    rem Has the user input a string at all?
    if not defined Version goto EnterVersion
    rem Remove all double quotes from user input string.
    set "Version=%Version:"=%"
    rem Is there no version string anymore after removing double quotes?
    if not defined Version goto EnterVersion
    rem Contains the version string any other character than digits and dots?
    for /F delims^=0123456789.^ eol^= %%I in ("%Version%") do goto EnterVersion
    
    rem Start demo.exe with the first argument -v and second argument being the
    rem input version string as new process with window title Demo in case of
    rem demo.exe is a console application in user's documents directory.
    start "Demo" /D"%USERPROFILE%\Documents" demo.exe -v %Version%
    
    endlocal
    

    要了解所使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。

    • echo /?
    • endlocal /?
    • for /?
    • goto /?
    • if /?
    • rem /?
    • set /?
    • setlocal /?
    • start /?

    另见

    【讨论】:

    • 它不断地问我“请输入版本”,是什么原因。?
    • 如果您使用仅包含我发布的代码的批处理文件并在提示符下输入2019.1.133,则输入字符串通过验证行。请阅读批处理文件中以命令rem 开头的注释行。但是,如果您将批处理文件中的代码与您未发布的上面和下面的其他行一起使用,那么由于第一段中解释的原因,它可能会失败。请编辑您的问题并添加您的真实代码。查看帮助主题How to create a Minimal, Complete, and Verifiable example?
    猜你喜欢
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2018-08-11
    • 2019-01-27
    • 2014-02-08
    相关资源
    最近更新 更多