2017-06-02 102 views
3

嗨,我試圖找到一種方法來從蝙蝠腳本獲得我自己的PID。 我發現這一點:從跑蝙蝠腳本獲取PID

title=mycmd 
tasklist /v /fo csv | findstr /i "mycmd" 

輸出:

"cmd.exe","15084","RDP-Tcp#5","2","2,768 K","Running","MEDIASERVER\Administrator 
","0:00:00","Administrator: =mycmd" 

我怎麼會得到PID號到我的蝙蝠腳本變量?

任何幫助,將不勝感激。

回答

3

嘗試getcmdpid,這樣你就不會需要更改標題:

title mycmd 
for /f "tokens=2 delims=," %%a in (
    'tasklist /v /fo csv ^| findstr /i "mycmd"' 
) do (
    set "mypid=%%~a" 
) 
echo %mypid% 

檢查也:

call getCmdPID.bat 
echo %errorlevel% 

與任務列表,你需要的循環處理輸出做此線程: http://www.dostips.com/forum/viewtopic.php?t=6133

+0

乾杯,完美的作品:) – StrayanDropbear

4
@echo off 
    setlocal enableextensions disabledelayedexpansion 

    rem Prepare a temporary file reference where to send the wmic output 
    for %%t in ("%temp%\%~nx0.%random%%random%%random%%random%%random%.tmp") do > "%%~ft" (

     rem Call wmic to retrieve its own parent process ID, that is, our cmd instance 
     wmic process where "name='wmic.exe' and commandline like '%%_%random%%random%%random%_%%'" get parentprocessid 

     rem Read the PID from the generated temporary file 
     for /f "skip=1" %%a in ('type "%%~ft"') do set "processID=%%a" 

     rem And remove the temporary file 
    ) & 2>nul del /q "%%~ft" 

    echo %processID%