2

我正在尝试使用带有批处理脚本的一些 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%

是语法问题吗?

4

1 回答 1

4

如果没有错误消息,我只能猜测。

您是否启用了延迟扩展?见setlocal /?

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

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

示例:(一次运行.bat一次,EnableDepayedExpansion一次不运行,你会看到区别。)

setlocal EnableExtensions EnableDelayedExpansion

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

endlocal
于 2013-01-05T21:56:09.523 回答