2016-08-22 88 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輸出中的用戶名之後。

相關問題