Batch file 意外使用(批处理文件)

Batch file 意外使用(批处理文件),batch-file,Batch File,在下面的代码中,如果发现正在运行,我想终止ABClient.exe和ABClientMonitor.exe。但是,当尝试运行代码时,我得到了一个意外使用(错误 代码: 括号内声明的变量需要用延迟扩展调用,否则它们实际上不存在。在这种情况下,由于%process1lvl%和%process2lvl%变量的位置,内部if语句的计算结果为if==0(,这会导致语法错误 要更正此问题,请在脚本开头添加行setlocal enabledelayedexpansion,并将%process1lvl%替换为!

在下面的代码中,如果发现正在运行,我想终止
ABClient.exe
ABClientMonitor.exe
。但是,当尝试运行代码时,我得到了一个
意外使用(
错误

代码:


括号内声明的变量需要用延迟扩展调用,否则它们实际上不存在。在这种情况下,由于
%process1lvl%
%process2lvl%
变量的位置,内部
if
语句的计算结果为
if==0(
,这会导致语法错误

要更正此问题,请在脚本开头添加行
setlocal enabledelayedexpansion
,并将
%process1lvl%
替换为
!process1lvl!
,将
%process2lvl%
替换为
!process2lvl!

@echo off
setlocal enabledelayedexpansion
color 0b
:loop
tasklist | find /i "ABClient.exe" > nul
set processFound1=%errorlevel%
tasklist | find /i "ABClientMonitor.exe" > nul
set processFound2=%errorlevel%
if %processFound1% == 0 (
    echo ABClient has been detected. Terminating...
    taskkill /f /im "ABClient.exe" > nul
    set process1lvl=!errorlevel!
    if !process1lvl! == 0 (
        echo ABClient has been terminated successfully!
        goto loop2
    ) ELSE (
        echo Failed to terminate ABClient!
        goto loop2
    )
)
:loop2
if %processFound2% == 0 (
    echo ABClientMonitor has been detected. Terminating...
    taskkill /f /im "ABClientMonitor.exe" > nul
    set process2lvl=!errorlevel!
    if !process2lvl! == 0 (
        echo ABClientMonitor has been terminated successfully!
        goto loop
    ) ELSE (
        echo Failed to terminate ABClientMonitor!
    goto loop
    )
)

谢谢!只是想知道,如果一个变量在一个括号内-在一个括号内,我会怎么做。它还会是吗!变量!?是的,任何时候一个变量至少在一组括号内,你都需要延迟展开,否则变量的值将不会更新。
@echo off
setlocal enabledelayedexpansion
color 0b
:loop
tasklist | find /i "ABClient.exe" > nul
set processFound1=%errorlevel%
tasklist | find /i "ABClientMonitor.exe" > nul
set processFound2=%errorlevel%
if %processFound1% == 0 (
    echo ABClient has been detected. Terminating...
    taskkill /f /im "ABClient.exe" > nul
    set process1lvl=!errorlevel!
    if !process1lvl! == 0 (
        echo ABClient has been terminated successfully!
        goto loop2
    ) ELSE (
        echo Failed to terminate ABClient!
        goto loop2
    )
)
:loop2
if %processFound2% == 0 (
    echo ABClientMonitor has been detected. Terminating...
    taskkill /f /im "ABClientMonitor.exe" > nul
    set process2lvl=!errorlevel!
    if !process2lvl! == 0 (
        echo ABClientMonitor has been terminated successfully!
        goto loop
    ) ELSE (
        echo Failed to terminate ABClientMonitor!
    goto loop
    )
)