2

How to kill specific VBScript using batch file?

@echo off
set vbs="%temp%\dummy.vbs"

for /f "usebackq tokens=2" %%s in (`WMIC path Win32_Process where 'name="wscript.exe"' get commandline,processid | findstr /i /c:"%vbs%"`) do (
    taskkill /f /fi "pid eq %%s"
)

I also tried the code below but it seems that commandline like is not working.

WMIC path Win32_Process where "name='wscript.exe' and commandline like %vbs%" get processid

Thanks in advance!

de.vina
  • 116
  • 10
  • 1
    You can't use single quotes to enclose the command **and** use it also inside the command, I'd switch to enclose the command with backquotes and insert `usebackq` --> `for /f "usebackq tokens=2" %%s in (\`WMIC path Win32_Process where 'name="wscript.exe"' ...` –  Sep 20 '18 at 10:54
  • 1
    The 'like' syntax, whilst correct in a Command Prompt, requires the `%` characters doubling in a batch file; e.g. `@WMIC Process Where "Name='wscript.exe' And CommandLine Like '%%vbs%%'" Call Terminate 2>Nul` – Compo Sep 20 '18 at 12:18
  • 1
    `set vbs="%temp%\dummy.vbs"` is not right. Right is `set "vbs=%temp%\dummy.vbs"`. It makes a big difference if first double quote is left to variable name or right to equal sign. For details see [Why is no string output with 'echo %var%' after using 'set var = text' on command line?](https://stackoverflow.com/a/26388460/3074564) – Mofi Sep 20 '18 at 15:18
  • Thanks guys! I was able to make it work with your comments. – de.vina Sep 21 '18 at 00:54

1 Answers1

2

Incorporated items in the comments and escaped special characters with ^.

@echo off

set "vbs=%temp%\dummy.vbs"

for /f "usebackq tokens=3" %%s in (
    `WMIC process where "name='wscript.exe'" get commandline^,processid ^| findstr /i /c:"%%vbs%%"`
) do (
    taskkill /f /fi "pid eq %%s"
)
de.vina
  • 116
  • 10