我试图找到一个正在运行的进程并使用 PSLIST 和 PSKILL 杀死它,但是,我无法正确设置错误级别。根据我的操作方式,它会卡在 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 命令返回正确匹配的错误级别?

最佳答案

使用pslist的-e参数怎么样?

pslist -e notepad
找到时会将错误级别设置为 0,未找到时将设置为 1。它也是完全匹配的,这意味着它不会识别 Notepad++ 。
PSList Help
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

关于batch-file - 如何在 Batch/CMD 中使用 PSLIST 和 FIND 查找精确匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17576984/

10-13 07:24