windows batch command to determine working directory of a process

后端 未结 3 1002
予麋鹿
予麋鹿 2020-12-16 17:12

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 orph

3条回答
  •  失恋的感觉
    2020-12-16 17:36

    Handle is an utility that displays information about open handles for any process in the system. You can use it to see the programs that have a file open, or to see the object types and names of all the handles of a program.

    Its GUI-based version is Process Explorer .

    handle -p yourProcess.exe  > log.txt
    

    It'll list all handles for yourProcess.exe in log file and now using batch command you can easily extract 'current working directory' of yourProcess from log.txt.

    added by barlop

    here is the output.. for process c:\tinyweb\tiny.exe run from c:\tinyweb\rrr

    C:\Users\user>handle -p tiny.exe
    
    Nthandle v4.1 - Handle viewer
    Copyright (C) 1997-2016 Mark Russinovich
    Sysinternals - www.sysinternals.com
    
    ------------------------------------------------------------------------------
    tiny.exe pid: 20668 compA\user
       10: File          C:\Windows
       1C: File          C:\tinyweb\rrr
       9C: File          C:\tinyweb\rrr\access_log
       A0: File          C:\tinyweb\rrr\agent_log
       A4: File          C:\tinyweb\rrr\error_log
       A8: File          C:\tinyweb\rrr\referer_log
       E4: Section       \Sessions\1\BaseNamedObjects\__wmhr_msgs_buffer_name$1e74
       EC: File          C:\Windows\winsxs\x86_microsoft.windows.common-controls_659
    
    C:\Users\user>
    

    If you want to parse it specifically then you could do it in pure cmd.exe with e.g. for /f, or with a third party scripting language like ruby, or with windows ports of various *nix style command line tools. This line uses such tools and gets it (obviously the following line requires grep and sed, preferably decent versions of them e.g. from cygwin)

    C:\Users\harvey>handle -p tiny.exe | grep "pid:" -A 3 | sed -n "3p" | grep -o ".:[\]\S*"
    C:\tinyweb\rrr
    

提交回复
热议问题