这个批处理脚本的语法有什么问题?

时间:2013-01-05 20:42:47

标签: windows-7 command-line putty batch-file

我正在尝试使用批处理脚本的一些SSH密钥自动加载Putty Pageant,但是因为我想绕过它已经运行的Pageant的错误消息,所以我将它放在IF语句中。但是出于某种原因,它不起作用:

tasklist /FI "IMAGENAME eq pageant.exe" 2>NUL | find /I /N "pageant.exe">NUL
if %ERRORLEVEL%==1 ( :: checks whether pageant.exe is running or not

    :: set the SSH-keys
    if exist "C:\SSH keys\key1.ppk" (set KEYS="C:\SSH keys\key1.ppk")
    if exist "C:\SSH keys\key2.ppk" (set KEYS=%KEYS% "C:\SSH keys\key2.ppk")

    if not defined KEYS (
        msg * A SSH-key is propably missing.
    )

    :: Start pageant with the defined SSH-keys
    start /d"C:\Program Files (x86)\PuTTY" pageant.exe %KEYS%

)

虽然他们分开工作: (1)

 tasklist /FI "IMAGENAME eq pageant.exe" 2>NUL | find /I /N "pageant.exe">NUL
 if %ERRORLEVEL%==1 ( :: checks whether pageant.exe is running or not

       :: This works!
       start /d"C:\Program Files (x86)\PuTTY" pageant.exe

 )

(2)

:: set the SSH-keys
if exist "C:\SSH keys\key1.ppk" (set KEYS="C:\SSH keys\key1.ppk")
if exist "C:\SSH keys\key2.ppk" (set KEYS=%KEYS% "C:\SSH keys\key2.ppk")

if not defined KEYS (
    msg * A SSH-key is propably missing.
)

This works as well!
start /d"C:\Program Files (x86)\PuTTY" pageant.exe %KEYS%

这是语法问题吗?

1 个答案:

答案 0 :(得分:4)

没有错误信息,我只能猜测。

您是否启用了延迟扩展?请参阅setlocal /?

将此添加到脚本的开头 setlocal EnableExtensions EnableDelayedExpansionendlocal到您脚本的末尾。

这允许KEYS变量评估实际值。延迟扩展允许将值立即设置为变量,而不仅仅是if语句的范围结束时。另外,请不要忘记在if语句中设置的变量使用!而不是%

示例:(使用.batEnableDepayedExpansion内运行一次,不使用一次,您将看到差异。)

setlocal EnableExtensions EnableDelayedExpansion

set "Value=Hello World"
echo %Value%
if 1==1 (
    set "Value=Goodbye World"
    echo %Value%
    echo !Value!
)
echo %Value%

endlocal