与批处理文件中的enabledelayedexpansion一起使用时,IF不起作用

时间:2015-09-09 02:10:37

标签: batch-file if-statement command-line

此批处理文件将终止psList找到的所有进程,但白名单除外。以下代码中的最终IF,我需要杀死非白名单进程,不起作用,我不知道为什么。怎么样?

            @echo off

            REM cd to the dir where this .bat file is in.
            cd /d %0\.. 

            setlocal enabledelayedexpansion 
            REM If we don't do enabledelayedexpansion, the variables won't be able to hold values and will only store blanks. Also we need to show variables like this : !variable! instead of %variable%. http://superuser.com/questions/78496/variables-in-batch-file-not-being-set-when-inside-if

            :: Goal : Kill all processes except those whitelisted.

            for /f "skip=3 tokens=1" %%i in ('pslist -accepteula') do (

                rem Set a variable to indicate if we kill the task or not. Boolean.
                set bKill=1 

                :: Whitelist : 
                if "%%i"=="svchost" SET bKill=0
                if "%%i"=="explorer" SET bKill=0
                if "%%i"=="cmd" SET bKill=0
                if "%%i"=="tasklist" SET bKill=0
                if "%%i"=="searchui" SET bKill=0
                if "%%i"=="lsass" SET bKill=0
                if "%%i"=="dwm" SET bKill=0
                if "%%i"=="sihost" SET bKill=0 
                if "%%i"=="dllhost" SET bKill=0 

                echo.
                echo %%i
                echo bkill value is = !bKill!
                :: I cannot make the following line to work: 
                if "!bKill!"=="1" @echo It works.
                :: The following line is the line I really want to work in the end. To troubleshoot the "if" and keep it simple I've replaced what was after the IF by an echo (line above).
                rem if "!bKill!"=="1" pskill -accepteula -t  "%%i" 

                pause

            )

1 个答案:

答案 0 :(得分:1)

set bKill=1 
           ^ Ending space included in value

由于包含空格,测试

if "!bKill!"=="1" @echo It works.
if      "1 "=="1" @echo It works

永远不会被评估为真。

更好地使用

set "bKill=1"

防止包含不需要的空格