2013-01-05 82 views
2

我试图用批处理脚本自动加载Putty Pageant与一些SSH密钥,但是因为我想绕过已经运行的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% 

它是一个语法问题?

+0

一种工作#1? –

+1

@GuyThomas堆栈溢出并不是特别满意的问题,只是由代码和修复请求组成。 OP应该说明究竟是什么失败,而不是说“它不起作用”,并显示他们已经把问题缩小到了什么程度。批处理脚本问题在这里是主题,不需要迁移,特别是当涉及编写甚至不需要编程(例如PuTTy)的软件的脚本时。 – slhck

回答

4

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

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

给你的脚本 setlocal EnableExtensions EnableDelayedExpansionendlocal的beggining添加到您的脚本的末尾。

这允许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 
+0

这听起来很有希望。明天我会试试。提前致谢! – jroeleveld

+0

太棒了!这样可行。这确实是EnableDepayedExpansion和惊叹号的结合。 – jroeleveld