从 运行 bat 脚本获取 PID
Getting PID from running bat script
您好,我正在尝试找到一种从 bat 脚本获取我自己的 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 编号放入我的 bat 脚本中的变量中?
如有任何帮助,我们将不胜感激。
尝试使用 getcmdpid ,因此您不需要更改标题:
call getCmdPID.bat
echo %errorlevel%
要使用任务列表执行此操作,您需要循环来处理输出:
title mycmd
for /f "tokens=2 delims=," %%a in (
'tasklist /v /fo csv ^| findstr /i "mycmd"'
) do (
set "mypid=%%~a"
)
echo %mypid%
@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%
您好,我正在尝试找到一种从 bat 脚本获取我自己的 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 编号放入我的 bat 脚本中的变量中?
如有任何帮助,我们将不胜感激。
尝试使用 getcmdpid ,因此您不需要更改标题:
call getCmdPID.bat
echo %errorlevel%
要使用任务列表执行此操作,您需要循环来处理输出:
title mycmd
for /f "tokens=2 delims=," %%a in (
'tasklist /v /fo csv ^| findstr /i "mycmd"'
) do (
set "mypid=%%~a"
)
echo %mypid%
@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%