如何在批处理/CMD中使用PSLIST和FIND找到精确匹配

3
我正在尝试使用PSLIST和PSKILL查找并杀死运行中的进程,但是无法正确设置errorlevel。根据我的操作方式,它会被卡在0或1上。我最初使用Taskkill和Tasklist命令使代码工作,但是代码必须在Windows 2000和XP上运行。我同时在运行notepad++编辑批处理文件。以下代码不能区分notepad++和notepad.exe。
@echo off

reg.exe ADD "HKCU\Software\Sysinternals\PsKill" /v EulaAccepted /t REG_DWORD /d 1 /f >NUL
reg.exe ADD "HKCU\Software\Sysinternals\PsList" /v EulaAccepted /t REG_DWORD /d 1 /f >NUL

rem just to see output of pslist
PSLIST "notepad" 2>NUL
ECHO.
ECHO. 
PSLIST "notepad" 2>NUL | FIND /I /N "notepad"
echo The error level is %errorlevel%


IF %errorlevel% EQU 0 (
    ECHO Notepad is running and will be terminated.
    ECHO.
    PSKILL "notepad.exe" 2>NUL
)
IF %errorlevel% EQU 1 (
    ECHO Notepad was not running.
    ECHO Starting Notepad now...
    ECHO.
    start "" "notepad.exe"
)

Pause
EXIT

上面的代码卡在了0。当我将FIND命令的那一行改为FINDSTR,如下所示:PSLIST "notepad" 2>NUL | FINDSTR /I /N "notepad.exe",那么它会卡在1。
有没有办法让PSLIST和FIND或FINDSTR命令找到完全匹配并返回正确的错误级别?
2个回答

3
使用pslist的-e参数如何?
pslist -e notepad

当找到时,它将设置错误级别为0,未找到时为1。此外,这是一个精确匹配,意味着它不会识别notepad ++。

PSList帮助

pslist v1.3 - Sysinternals PsList
Copyright (C) 2000-2012 Mark Russinovich
Sysinternals - www.sysinternals.com

Usage: pslist [-d][-m][-x][-t][-s [n] [-r n] [\\computer [-u username][-p password][name|pid]
   -d          Show thread detail.
   -m          Show memory detail.
   -x          Show processes, memory information and threads.
   -t          Show process tree.
   -s [n]      Run in task-manager mode, for optional seconds specified.
               Press Escape to abort.
   -r n        Task-manager mode refresh rate in seconds (default is 1).
   \\computer  Specifies remote computer.
   -u          Optional user name for remote login.
   -p          Optional password for remote login. If you don't present
               on the command line pslist will prompt you for it if necessary.
   name        Show information about processes that begin with the name
               specified.
   -e          Exact match the process name.
   pid         Show information about specified process.

All memory values are displayed in KB.
Abbreviation key:
   Pri         Priority
   Thd         Number of Threads
   Hnd         Number of Handles
   VM          Virtual Memory
   WS          Working Set
   Priv        Private Virtual Memory
   Priv Pk     Private Virtual Memory Peak
   Faults      Page Faults
   NonP        Non-Paged Pool
   Page        Paged Pool
   Cswtch      Context Switches

我忘了提到我之前尝试过那个方法但没有成功,但是既然你提到了它并且现在似乎能够起作用,我决定再次尝试一下。我不确定之前我做错了什么。这是新的代码行... PSLIST "notepad" 2>NUL 我去掉了 FIND 命令,现在似乎返回了正确的错误级别。谢谢。 - ucfmat

2

试一下这个(只显示有用的那行):

PSLIST "notepad++" 2>NUL | FINDstr /I "notepad++"
echo %errorlevel%
PSLIST "notepad" 2>NUL | FINDstr /I "notepad[^+]"
echo %errorlevel%

这在Windows 7中似乎效果很好,但当我切换到XP系统时,“notepad”这一行似乎无法产生正确的结果。它仍然给出错误级别为零的回显,即使它说没有找到记事本。奇怪。 - ucfmat
我在使用XP系统,这里运行良好。请检查您的PSLIST版本。我的代码中的Errorlevel是由findstr产生的。 - Endoro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接