2016-08-22 81 views
-1

我必须向执行特定进程的多个用户发送msg: 如何查找用户名列表,例如执行图像“chrome”。 exe“,然后将msg发送给这些用户。 上述所有活动必须在蝙蝠文件中 提前谢谢!如何查找运行特定进程的用户列表

+2

为什么*必须*它是一个批处理文件?微软现代化的首选系统脚本和管理工具PowerShell将使*更容易*。家庭作业,也许? – alroc

回答

2

基础上意见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,我想没有人会注意到这一点)

+0

也是一个很好的解决方法!虽然'@'可能出现在图像和/或会话名称中,所以也许这是一个好主意,以切换到禁止的字符(例如'','''等等)...或者,让一个[标准'for'循环处理逗号和引号](http:// stackoverflow .com/a/39081459)... ;-) – aschipfl

+0

@aschipfl通常,如果我需要保存分隔符,我倾向于使用0x254 – Stephan

+0

但是这是代码页相关的,并且它也允许在进程文件/映像/会话名称... – aschipfl

1

试试这个:

@echo off 
for /f "tokens=8" %%i in ('tasklist /fi "imagename eq chrome.exe" /fo table /nh /v') do echo %%i 

请注意,如果图像名称中包含空格的代码可能是马车,但我找不到纯批处理文件的完美解决方案。

说明:

screenshot

+0

空格并不重要,如果你使用你的注释('/ fo csv')的方法并适应你的'for'一点:'for/f“标记= 7 delims =,”%% a in(' tasklist/fi“imagename eq firefox.exe”/ fo csv/nh/v')do echo %%〜a' – Stephan

+0

@Stephan但是'32,500 K'呢? – xmcp

+0

请尝试;应该因报价而工作;无法验证(我的系统说'32.500 K') – Stephan

0

xmcpanswer给出了完美的命令检索进程和其所属的用户的名称。但是,如果数据中出现额外的空格,则它们的解决方案将失败。

为了使它更安全,由标准for循环使用tasklist命令的输出格式,捕捉由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输出中的用户名之后。

相关问题