差異處
這裏顯示兩個版本的差異處。
下次修改 | 前次修改 | ||
windowsbatch:killprocwithcli [2013/02/25 13:38] 127.0.0.1 外部編輯 |
windowsbatch:killprocwithcli [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>WindowsBatch}} | + | {{tag>WindowsBatch wmic}} |
====== 如何根據CommandLine去砍掉你要砍的行程? ====== | ====== 如何根據CommandLine去砍掉你要砍的行程? ====== | ||
===== 源起 ===== | ===== 源起 ===== | ||
行 111: | 行 111: | ||
要啟用延遲展開變數,可以透過cmd /v或是setlocal enabledelayedexpansion。\\ | 要啟用延遲展開變數,可以透過cmd /v或是setlocal enabledelayedexpansion。\\ | ||
+ | |||
+ | ==== 解決findstr出現line xx is too long的問題 ==== | ||
+ | 由於findstr長度限制為127個字元,假如commandline很長,wmic後的結果一定會有問題。一開始想透過find解決這個問題,但使用後發現難以產生期望輸出。最後是透過WQL去針對commandline與name欄位做過濾,在執行完wmic後,一樣透過findstr去找尋預期程序開頭的行,然後取pid。另外我有針對輸入參數做判斷,程序名稱不得為空,而commandline如果為空就會去砍掉所有輸入名稱的程序。(程序名稱為空會砍掉所有的..) | ||
+ | <file bash killProc.bat> | ||
+ | @echo off | ||
+ | setlocal enabledelayedexpansion | ||
+ | set PROC_NAME=%1 | ||
+ | set COND=%2 | ||
+ | |||
+ | if "%PROC_NAME%"=="" ( | ||
+ | echo Process' name can't be empty. | ||
+ | exit /b 1 | ||
+ | ) | ||
+ | |||
+ | if "%COND%"=="" ( | ||
+ | set CMD_GET_PROC=wmic path win32_process where "Name like '%%%PROC_NAME%%%'" get Processid^^,Caption ^^^| findstr "^%PROC_NAME%" | ||
+ | ) else ( | ||
+ | set CMD_GET_PROC=wmic path win32_process where "Commandline like '%%%COND%%%' and Name like '%%%PROC_NAME%%%'" get Processid^^,Caption ^^^| findstr "^%PROC_NAME%" | ||
+ | ) | ||
+ | |||
+ | set last= | ||
+ | for /f "usebackq tokens=*" %%r in (`%CMD_GET_PROC%`) do ( | ||
+ | for %%t in (%%r) do set last=%%t | ||
+ | taskkill /f /pid !!last! | ||
+ | ) | ||
+ | </file> | ||
其它所作的內容就不贅述了,真的有問題再來問我吧!\\ | 其它所作的內容就不贅述了,真的有問題再來問我吧!\\ | ||
\\ | \\ | ||
+ | ===== ===== | ||
友藏內心獨白: 寫完這個batch,功力又提升更多了。 | 友藏內心獨白: 寫完這個batch,功力又提升更多了。 | ||
+ | ===== Reference ===== | ||
+ | * [[https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/n36VGULacVU|findstr目標字串長度過長問題]] | ||
+ | * [[http://cnkmym.blogspot.tw/2011/10/why-java-hang-when-invoking-wmic.html|Why java hang when invoking wmic?]] | ||
===== 後記 ===== | ===== 後記 ===== | ||
- | * 2012-09-18 實際使用遇到了block問題。原因是因為透過java程式呼叫時,WMIC其標準輸入導致block,oogle可以找到相關資訊。最後透過ant呼叫解決。 | + | * 2012-09-18 實際使用遇到了block問題。原因是因為透過java程式呼叫時,WMIC其標準輸入導致block,google可以找到相關資訊。最後透過ant呼叫解決。 |
+ | * 2013-07-30 遇到findstr去過濾process command line長度過長問題。改透過WQL去做filter解決。 | ||
+ | * 2013-08-08 找到解決在Windows2003中,透過java程式呼叫wmic block的問題。在command line最後加入<NUL即可解決。Exmaple. wmic xxx ^^^<NUL ^^^| findstr xxxx | ||
===== ===== | ===== ===== | ||
---- | ---- | ||
\\ | \\ | ||
~~DISQUS~~ | ~~DISQUS~~ |