Search code examples
windowsbatch-filecmdwmic

fix loop to save essential windows processes, with its path, and kill the rest processes


I want to save the some system processes, with its path, to ensure that the system does not crash, and kill the rest of process

example: lsass.exe, winlogon.exe, conhost.exe, rundll32.exe, etc

This is my .bat:

set proc=,
:: proc
call:proc "lsass.exe"
call:proc "winlogon.exe"
call:proc "conhost.exe"
call:proc "rundll32.exe"

for /f "skip=3 tokens=1 delims= " %%a in ('tasklist /fi "username eq %username%"') do (
echo %proc%, | findstr /c:,%%a, 1>nul
if errorlevel 1 (
taskkill /f /im %%a /t
) else (
echo not kill
)
)

:: funcion proc
@echo off
pause
goto:eof
:proc
set getproc=%1
for /f "tokens=1 delims=," %%F in ('tasklist /nh /fi "imagename eq %getproc%" /fo csv') do set proc=%proc%,%%~F>nul
goto:eof

The problem is that my script does not save the path of the process, then, if there is a fake process running in another location, my script saves both processes. That's why I need to save the Windows system process including its original path

Example real process:

wmic process where "name='lsass.exe'" get ExecutablePath

Out real process:

C:\Windows\system32\lsass.exe

Example fake process:

Out XP:

 C:\Documents and Settings\User\Local settings\Application Data\lsass.exe

or Out 7

 C:\Users\User\AppData\Roaming\lsass.exe
 c:\Users\User\Local Setting\Temp\lsass.exe
 c:\Users\User\AppData\Local\lsass.exe

Note: Fake processes can be run from any path (.exe files associated with false process can be stored anywhere on the PC), except system folders (% windir%/system32 %windir%/sysWOW64 %windir%, etc)

Unfortunately, until now, My script does not close the fake processes, and only I could close manually using Process Explorer

request: What I need is to save the real processes, with its original path (lsass.exe, winlogon.exe, etc), and kill the rest. Thanks


Solution

  • Check this solution, by @JosefZ

    @ECHO OFF
    SETLOCAL EnableExtensions DisableDelayedExpansion
    
    REM note double quotes                          REM added for debugging ↓↓↓↓↓↓↓↓↓↓↓↓
    set "_var="%userprofile%","%Appdata%","%HOMEPATH%","%homedrive%\ProgramData","D:\Remote""
                                                    REM added for debugging ↑↑↑↑↑↑↑↑↑↑↑↑
    
    REM wmic requires double backslashes in specified path 
    set "_var=%_var:\=\\%"
    
    for %%G in  (%_var%) do (
    rem echo processing %%G
      REM used `GET Caption` for debugging
    rem WMIC PROCESS WHERE "Name = '%~1' and ExecutablePath Like '%%%%~G%%'" GET Caption
    
      REM operational 
    WMIC PROCESS WHERE "Name = '%~1' and ExecutablePath Like '%%%%~G%%'" Call terminate 
    )