Jim_Lafleur
Jim_Lafleur

Reputation: 3

IF doesnt work when used with enabledelayedexpansion in batch file

This batch file will kill all processes found by psList, except for those whitelisted. The final IF in the following code, that I need to kill the non-whitelisted processes, doesn't work and I don't know why. How come?

            @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

            )

Upvotes: 0

Views: 116

Answers (1)

MC ND
MC ND

Reputation: 70923

set bKill=1 
           ^ Ending space included in value

As there is an space included, the test

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

will never be evalueated to true.

Better use

set "bKill=1"

preventing the inclusion of unneeded spaces

Upvotes: 1

Related Questions