windows batch command to determine working directory of a process

user972276 picture user972276 · Dec 13, 2013 · Viewed 11.4k times · Source

Why I ask is that my program uses 3rd party software that sometimes leaves behind orphan processes that have no link back to my program or the 3rd party process. These orphan processes start to add up and consume tons of resources over time. I would like to kill them off periodically, but in order for me to do that, I need to know for sure they were created by my program and not some other program. I have viewed the orphan processes in Process Explorer and when looking at the properties of the process, I see a field called "Current Directory". The current directory for the orphaned process is the install directory of my program. This would give me reassurance I am killing a process created by my program.

Since these processes are created by a 3rd party, I need to just kill them after they are created by running taskkill on them or something. Is there a way to figure out the current working directory of a process using out of the box windows commands in a batch file? If this can be done through wmic queries that would be preferable, but I cannot seem to find the current working directory when using wmic. I assume if Process Explorer is able to obtain this info, I should be able to get it too through some batch commands.

Answer

wdscxsj picture wdscxsj · Sep 15, 2014

tlist from WDK to the rescue! The 2nd line of its output ("CWD: ...") shows the working directory of a process:

> tlist 944
 944 postgres.exe
   CWD:     D:\Lab\Database\pgsql\test\
   CmdLine: "D:/Tools/pgsql/bin/postgres.exe"  -D "."
   VirtualSize:   221116 KB   PeakVirtualSize:   242620 KB
   WorkingSetSize: 17076 KB   PeakWorkingSetSize: 19336 KB
   NumberOfThreads: 4
   9084 Win32StartAddr:0x00000000 LastErr:0x00000000 State:Waiting
   8504 Win32StartAddr:0x00000000 LastErr:0x000000b7 State:Waiting
   8616 Win32StartAddr:0x00000000 LastErr:0x00000000 State:Waiting
   7468 Win32StartAddr:0x00000000 LastErr:0x00000000 State:Waiting
    9.3.5.14202 shp  0x0000000000400000  D:\Tools\pgsql\bin\postgres.exe
 6.1.7601.18247 shp  0x00000000770D0000  C:\Windows\SYSTEM32\ntdll.dll
 ...

See the doc for more info.