Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

im trying to find a way to get my own PID from a command prompt (for later use in bat scripts) so far the only useful way i found was to use getpids.exe from here : http://www.scheibli.com/projects/getpids/index.html but im looking for a command that's "built in" to windows

edit : im looking for a "bullet proof" way - no assumptions about my process being the only cmd.exe or anything

share|improve this question
    
Are you looking for a command-line tool that displays the PID of the CMD.exe you are running it in? –  uSlackr Mar 26 '10 at 14:06

7 Answers 7

up vote 9 down vote accepted

Since none of the above solutions are bullet proof and built-in, I figured I'd add my little routine that closer to bullet proof but you'll need to parse/save the results somehow

do this if you can within the batch file

title=mycmd
tasklist /v /fo csv | findstr /i "mycmd"
share|improve this answer
    
thats really neat. im pretty sure the current time + some randomly-generated number can be set as the title to get near bulletproof –  radai Mar 29 '10 at 10:49
    
Don't use %random% + %time% if you have a scheduler call your batch script twice at the same time. I had the issue that the same script was called with different parameters at the same time. The seed for random was the same and I ran into collisions when creating a temporary directory. There was no way around then to handle the error when creating the temporary directory. Long story short, if you can assume that your script does not get fired of twice at the same time, this trick should work. –  Peter Schuetze Nov 11 at 17:05
    
Might be (not deeply tested) that getting a more precise timestamp (including microseconds, rather than 1/100 seconds like in %time%), would be more reliable in this case: wmic os get LocalDateTime (YearMonthDayHourMinuteSecond.Microsecond+Timezone). Unless the scheduler is able to run two things in the exact same microsecond... –  Gauthier Boaglio Dec 15 at 6:38
  1. Windows Task Manager, you will need to go to View -> Select Columns.. and select PID.
  2. "tasklist /v" to get verbose task information in command prompt.
  3. Process Explorer from live.sysinternals.com.
share|improve this answer
    
@Vivek, from a command prompt... and you are duping answers –  WooYek Mar 27 '10 at 0:02
    
i just gave all possible options.. and no duplicating.. i could have also mentioned PowerShell but i restrained myself as that does not comes by default in XP and 2003. If this is for Vista onwards OS, Yes PowerShell would have been my preference. –  Vivek Kumbhar Mar 27 '10 at 0:24

This should do the trick:

tasklist /v

share|improve this answer

If you've got the Windows 2003 Resource kit push it through qgrep to get just the line you want. You could then extract the pid from here (this assumes you've only got one cmd running at a time),

tasklist /v | qgrep cmd

cmd.exe 2040 RDP-Tcp#447 0 1,804 K Running MACHINE\Administrator  0:00:00 Command Prompt
share|improve this answer

Take a look at this little batch trick. It sets the title of cmd to a special value then uses tasklist to find it. Inventive

\\Greg

share|improve this answer

If you want to find the PID of imagename "notepad.exe", then the following code will work for you:

for /F "tokens=1,2" %i in ('tasklist') do (
 if "%i" equ "notepad.exe" (set x=%j)
)
echo %x%
share|improve this answer

I believe the following is bulletproof, provided the user has access to WMIC and TEMP points to a valid path where the user has write privileges. This is the end result of some collaborative work at http://www.dostips.com/forum/viewtopic.php?f=3&t=6133.

@echo off

:getPID  [RtnVar]
::
:: Store the Process ID (PID) of the currently running script in environment variable RtnVar.
:: If called without any argument, then simply write the PID to stdout.
::
setlocal disableDelayedExpansion
:getLock
set "lock=%temp%\%~nx0.%time::=.%.lock"
set "uid=%lock:\=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:'=:q%"
set "uid=%uid:_=:u%"
setlocal enableDelayedExpansion
set "uid=!uid:%%=:p!"
endlocal & set "uid=%uid%"
2>nul ( 9>"%lock%" (
  for /f "skip=1" %%A in (
    'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
  ) do for %%B in (%%A) do set "PID=%%B"
  (call )
))||goto :getLock
del "%lock%" 2>nul
endlocal & if "%~1" equ "" (echo(%PID%) else set "%~1=%PID%"
exit /b

The script establishes an exclusive lock on a temporary file that incorporates the current time into the name. There can only be a collision if two like named batch processes attempt to get the PID within the same 0.01 second time interval, in which case only one will succeed.

Any process that fails will repeatedly loop back and try again with a new lock file path until it succeeds.

The full path to the lock file is transformed into a unique ID that can be used in the WMIC query. WMIC is run within a FOR /F command, which means it is running in a child cmd.exe process. That is why the ParentProcessID of the cmd.exe process is retrieved.

share|improve this answer
    
EDIT: Fixed minor bug dealing with potential for percent in a file path. Also eliminated trailing spaces from result. –  dbenham 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.