如何查找运行特定进程的用户列表
问题描述:
我必须向执行特定进程的多个用户发送msg: 如何查找用户名列表,例如执行图像“chrome”。 exe“,然后将msg发送给这些用户。 上述所有活动必须在蝙蝠文件中 提前谢谢!如何查找运行特定进程的用户列表
答
基础上意见xmcp的回答,我扩大代码位:
@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%x in ('tasklist /fi "imagename eq firefox.exe" /fo csv /nh /v') do (
set line=%%x
set line=!line:","="@"!
for /f "tokens=7 [email protected]" %%a in (!line!) do echo %%~a
)
它取代了字段分隔符(","
),而不触及逗号在数字内(在某些本地化中)并用不同的分隔符分析结果字符串。 Donwside:它会减慢速度(theroetical,我想没有人会注意到这一点)
答
试试这个:
@echo off
for /f "tokens=8" %%i in ('tasklist /fi "imagename eq chrome.exe" /fo table /nh /v') do echo %%i
请注意,如果图像名称中包含空格的代码可能是马车,但我找不到纯批处理文件的完美解决方案。
说明:
答
xmcp的answer给出了完美的命令检索进程和其所属的用户的名称。但是,如果数据中出现额外的空格,则它们的解决方案将失败。
为了使它更安全,由标准for
循环使用tasklist
命令的csv输出格式,捕捉由for /F
环路其输出以实线/行和提取单塔/小区项目:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem /* Capture CSV-formatted output without header; `tasklist` returns these columns:
rem `"Image Name","PID","Session Name","Session#","Mem Usage","Status","User Name","CPU Time","Window Title"`: */
for /F "delims=" %%L in ('
tasklist /FI "ImageName eq Chrome.exe" /FI "Status eq Running" /V /NH /FO CSV
') do (
rem // Initialise column counter:
set /A "CNT=0"
rem /* Use standard `for` loop to enumerate columns, as this regards quoting;
rem note that the comma `,` is a standard delimiter in `cmd`: */
for %%I in (%%L) do (
rem // Store item with surrounding quotes removed:
set "ITEM=%%~I"
rem /* Store item with surrounding quotes preserved, needed for later
rem filtering out of (unquoted) message in case of no match: */
set "TEST=%%I"
rem // Increment column counter:
set /A CNT+=1
rem // Toggle delayed expansion not to lose exclamation marks:
setlocal EnableDelayedExpansion
rem /* in case no match is found, this message appears:
rem `INFO: No tasks are running which match the specified criteria.`;
rem since this contains no quotes, the following condition fails: */
if not "!ITEM!"=="!TEST!" (
rem // The 7th column holds the user name:
if !CNT! EQU 7 echo(!ITEM!
)
endlocal
)
)
endlocal
exit /B
这只是回应当前运行名为Chrome.exe
的进程的每个用户的名称。要向他们发送消息,您可以使用net send
命令而不是echo
。
如果CSV数据包含全局通配符*
和?
,则此方法不起作用;这些字符不应该出现在图片,会话和名称中;它们可能会出现在窗口标题中,但它们出现在tasklist
输出中的用户名之后。
为什么*必须*它是一个批处理文件?微软现代化的首选系统脚本和管理工具PowerShell将使*更容易*。家庭作业,也许? – alroc