【问题标题】:Passing exclamation mark (!) to groovy script via Windows batch/command script通过 Windows 批处理/命令脚本将感叹号 (!) 传递给 groovy 脚本
【发布时间】:2019-04-25 16:56:34
【问题描述】:

从 Windows 命令行将包含感叹号 (!) 的参数传递给 groovy 脚本会被删除,因为 Windows 正在尝试使用延迟扩展来扩展变量名(请参阅thisthis 和 @ 987654323@)。发布了很多包含这些解决方案之一的解决方案:

  • setlocal ENABLEDELAYEDEXPANSION
  • 转义“带引号^!”
  • 不带引号转义^^!

这些都是公认的答案,所以显然它在某些情况下有效,但对我不起作用。这是我在 Windows 10 Professional 上遇到的行为:

C:\sof>type cmdtest.groovy
PASSWD=args[0]
println PASSWD

C:\sof>groovy cmdtest.groovy foopasswd!
foopasswd

C:\sof>groovy cmdtest.groovy foopasswd^^!
foopasswd

C:\sof>groovy cmdtest.groovy "foopasswd^!"
foopasswd

C:\sof>setlocal DisableDelayedExpansion

C:\sof>groovy cmdtest.groovy foopasswd!
foopasswd

C:\sof>groovy cmdtest.groovy foopasswd^^!
foopasswd

我认为这是在 groovy.bat 中以某种方式发生的,所以我也尝试将 setlocal DisableDelayedExpansion 添加到 groovy.bat,但它也没有工作。

能否以某种方式告诉我让上述cmdtest.groovy 尊重!的诀窍?

【问题讨论】:

    标签: batch-file groovy


    【解决方案1】:

    问题是文件groovy.batstartgroovy.bat,它们包含错误的批处理代码。
    startgroovy.bat 启用延迟扩展,但不使用它!

    通过在该行中使用%*,将参数从groovy.bat 传输到startgroovy.bat

    "%DIRNAME%\startGroovy.bat" "%DIRNAME%" groovy.ui.GroovyMain %*
    

    第一个插入符号将被删除,但有多少是不确定的,因为是否启用延迟扩展并不可靠。 在startgroovy.bat 中启用了延迟扩展,并且参数按set CP=%~2 之类的行存储。
    那里将删除下一个插入符号。
    但是当参数到达块时:

    rem escape minus (-d), quotes (-q), star (-s).
    set _ARGS=%*
    if not defined _ARGS goto execute
    set _ARGS=%_ARGS:-=-d%
    set _ARGS=%_ARGS:"=-q%
    ...
    

    所有希望都破灭了,这里不可能保留感叹号

    如果要修复此问题,则需要将所有 %ARGS:...% 表达式替换为 -!ARGS:...!

    set _ARGS=!_ARGS:-=-d!
    set _ARGS=!_ARGS:"=-q!
    

    但是函数:win9xME_args_loop也坏了。

    :win9xME_args_loop
    rem split args by spaces into first and rest
    for /f "tokens=1,*" %%i in (!_ARGS!) do call :get_arg "%%i" "%%j"
    goto process_arg
    

    call ... "%%i" "%%j" 不适用于插入符号/感叹号,必须将其重构为:

    for /f "tokens=1,*" %%i in ("!_ARGS!") do (
       set "_ARG=!_ARG! %%~i"
    

    但我的结论是:不要尝试在密码中使用特殊字符。
    必须完全重写 groovy 批处理文件,目前这些文件是反模式的一个很好的例子

    【讨论】:

    • 哈哈!谢谢你写的愉快而翔实的文章!如果它变得如此重要,我会保留参考作为指导,但现在会听取你的建议,并注意特殊字符。这是我们场景中的一个边缘案例,但它让我很生气,我想了解这个问题。感谢您的帮助。
    猜你喜欢
    • 2015-03-07
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2015-12-15
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多