windows batch command to determine working directory of a process - windows

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.

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.

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

The following will work, though you only need "CommandLine" or "ExecutablePath" - not both:
wmic process where "ProcessID=1111" get CommandLine, ExecutablePath
It will return something like the following, showing where the program for PID 1111 is running:
"C:\Program Files (x86)\Common Files\MyProgram\Agent\agent.exe"

Related

How do I find the path to the .exe file that created a process?

Preferably a command line tool to do this...
I understand that there is a program called tasklist.exe in Windows systems, and it has many powerful features to view processes currently running on the system.
Unfortunately it does not have the functionality to view the path of the .exe file that created or spawned the process in the first place.
I finally decided to take a tour of my system and I've noticed some shady looking processes and I want to check if they live in equally shady looking places on my system.
Any ideas?
You can use PowerShell.
Click Start -> Run, and type powershell to invoke Power Shell.
View all processes currently:
tasklist
Show full path of .exe file (Example command for Notepad++):
Get-Process notepad++ | Select-Object Path
You will see output:
Path
C:\Program Files (x86)\Notepad++\notepad++.exe

How do I convert .doc files to .txt using LibreOffice from the command line?

I have a folder of .doc files I would like to convert to .txt format. How can I do that using LibreOffice's command line mode in Windows 7? The files are located in C:\Temp\Test.
Here is how I handled this task using Windows PowerShell
Note: before using LibreOffice from the command line you need to close all existing instances of Libreoffice. This means closing all GUI sessions of LibreOffice as well as inspecting TaskManager for soffice.exe or a LibreOffice process running the background.
One Item:
PS &("C:\Program Files (x86)\LibreOffice 4\program\soffice.exe") -headless -convert-to txt:Text -outdir C:\Temp C:\Temp\test\sample.doc
This created a file sample.txt in C:\Temp from the document sample.doc
Multiple Items:
foreach ($file in Get-ChildItem C:\Temp\test)
{
&("C:\Program Files (x86)\LibreOffice 4\program\soffice.exe") -headless -convert-to txt:Text -outdir C:\Temp C:\Temp\test\$file | Out-Null
}
This created a .txt file for every file in the folder C:\Temp\test
Again: Use task manager to ensure that a previous version of soffice.exe is not running. This means closing existing GUI versions of LibreOffice.
Explanation:
Here is the documentation regarding Starting LibreOffice Software With Parameters. This will explain the soffice.exe command executed above.
Headless mode starts the LibreOffice software without a GUI. What I refer to in the question as 'command line mode'.
-convert-to is an important parameter in this example. When using -convert-to you need to know what the output_filter_name is (Text in the example above). A reference for those names can be found here. The output_filter_name will be the name of the files in that list that have the suffix .xcu
For example, if I wanted to convert my .doc files to .pdf I would use the parameter -convert-to pdf:writer_pdf_Export (untested)
Here is a reference I used when answering this question.
For some reason .exe processes need to pipe to Out-Null to avoid overlapping one another. Go figure.
The solution above was close, but required some alteration on LibreOffice 4.2 / Linux:
soffice --headless --convert-to txt:Text /path_to/file_to_convert.odt
(I did it with odt, the example I followed used doc: http://ask.libreoffice.org/en/question/14130/how-do-i-install-filters-for-the-soffice-command/)
An additional and important thing to add to #kevinaskevin 's answer is - the workaround is:
From the devs via IRC:
LO's "user installation" (i.e., ~/config/libreoffice) isn't designed to be accessed simultaneously by multiple processes; so when one soffice.bin is already running for a specific user installation, additional soffice.bin just forward their cmd line args to the first one and terminate immediately again (i.e., they shouldn't "fail" in the sense of exiting with a non-zero exit value)
if you want an independent headless LO, you can start it with an own user installation, -env:UserInstallation=<file URL to dir>

SysInternals Handle not showing my .txt file while it is open

I am writing a Windows shell script that works with lock files. For the sake of knowing if some file is locked, I am testing the Handle* utility from SysInternals that, according to its docs:
«Handle is a 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»
so I try it by creating a simple .txt file:
C:\Windows\system32>echo Foo >> Foo.txt
C:\Windows\system32>notepad Foo.txt
(notepad appears on screen with a new file named Foo.
C:\Windows\system32>handle Foo
Handle v3.51
Copyright (C) 1997-2013 Mark Russinovich
Sysinternals - www.sysinternals.com
No matching handles found.
What is going on here? My file is supposed to be open, and notepad should have a handle on it, but this line:
handle -p notepad | grep "Foo"
yields no results.
How can I use handle to know if my Foo.txt file is in use (locked)?
Maybe someone could give me some examples of the usage of handle.
Notepad reads the file into memory and closes the handle, which is why you don't see it open. You can see that behavior in a Process Monitor trace.
At first I guess that you forgot the file extension .txt in your command line, the second thing is I guess it will only show processes with a exclusive file lock which is not given by notepad.

Windows - Can not force close network file handle - Can not close system (Pid 4) file handles

Firstly, sorry for the long question, but I wanted to provide sufficient detail.
Synopsis:
In Windows does not appear to be possible to force close a file handle opened over a network share. Hence a file that is opened over a network share can not be moved/renamed/deleted. I am using Win 7.
Question:
Can anyone see what I am doing wrong or can someone confirm that this is as expected and it is not possible to force close system file handles (always on pid 4, such as those related to network share access to the file).
Background:
We have remote network client users who access a log file. We need to roll the log file so it does not grow too large. We can not roll the log file as the file is reported as in use.
Recreate Issue:
0)
Do everything as Administrator
1)
Create a new dir and share it
2)
Create a file in the new dir
3)
Via the file share edit the file with something that tends to get a file lock like MS Word. So do Start / Run then type in \YourHostName then select the file share you creaeted, then navigate to the file and edit it with Word. This is to simulate a remote user/host locking the file.
4)
List the open file handles, we can see 2 below
C:>handle C:\Log\MyLockedFile.txt
Handle v3.46
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com
System pid: 4 type: File 3E64: C:\Log\MyLockedFile.txt
System pid: 4 type: File 5E48: C:\Log\MyLockedFile.txt
5)
Try to close a file handle, here we see the attempt to close fail.
C:>handle -c 3E64 -p 4
Handle v3.46
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com
3E64: File (R--) C:\Log\MyLockedFile.txt
Close handle 3E64 in System (PID 4)? (y/n) y
Error closing handle:
The handle is invalid.
6)
List network file handles, here we see the opened network shares to the file.
C:>openfiles /query -v
INFO: The system global flag 'maintain objects list' needs
to be enabled to see local opened files.
See Openfiles /? for more information.
Files opened remotely via local share points:
Hostname ID Accessed By Type #Locks Open Mode Open File (Path\executable)
14693W7N 67109233 myuser1 Windows 0 Write + Read C:\Log\MyLockedFile.txt
14693W7N 495 myuser1 Windows 0 Read C:\Log\
7)
Close/disconnect file handles to the file, here it appears to work
C:>openfiles /disconnect /a * /OP C:\Log\MyLockedFile.txt
SUCCESS: The connection to the open file "C:\Log\MyLockedFile.txt" has been terminated.
8)
System file handle is still active even after attempting to delete it.
C:>handle C:\Log\MyLockedFile.txt
Handle v3.46
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com
System pid: 4 type: File 3E64: C:\Log\MyLockedFile.txt
9)
The file can not be moved/renamed as it is still in use
C:>move C:\Log\MyLockedFile.txt C:\Log\MyLockedFile.txt.newName
The process cannot access the file because it is being used by another process.
0 file(s) moved.
Just posting as an answer because saw this question hanging around answerless (heh, by holy chance, for EXACTLY one year?)
First, there is a really interesting discussion on this very topic here (about NTFS, I suppose). If you read the above link, you can get nice hints about why some handles seem to "hang" open forever, and why "forcing close" is not a very good idea.
The reason "handle -c" was giving an invalid handle error could have something to do with running "handle" locally and remotely, i.e. on the machine that the network drive is physically attached to (?)
For my own purposes, and in my own scenario, I ended up forcing close a handle remotely (just because I wanted to close it in a quick and dirty way - using Sysinternals tools you mentioned, namely "psexec" and "handle" (no need to specify user and password, given that I am logged in as administrator role, I guess) :
rem To list the open handles
psexec \\someserver -c handle /accepteula some_filename
rem To force close a particular handle
psexec \\someserver -c handle /accepteula -c 3F9C -p 4
But while running handle command remotely again didn't give any results (no open handles), the folder I was trying to delete was still locked. After some time (I also tried to disconnect from the network share in question using "net use f: /delete" to no avail, as it "was being accessed by an active process") - I figured out that my own local machine was still retaining open handles to that directory - and actually the handles I forced close remotely were from my own machine. I closed them without problems using Process Explorer GUI, which should be equal to using "handle" from the command prompt. After that the folder in question could be deleted.

Replacement for Vern Buerg's list.com in 64 bit Windows 7

I would like to find a replacement for list.com, specifically the ability to accept piped input. For example:
p4 sync -n | list
which accepts the output of the perforce command and displays the results in the viewer/editor for manipulation or saving. I know that I would send the output to a file and then open the file in the viewer/editor but I use it for temporary results.
List.com doesn't work on 64 bit Windows 7.
A good 32-bit Windows-based alternative to Vern Buerg's List is Charles Prineas' "V". Find it at http://www.fileviewer.com.
I believe someone is working on a replacment. See http://mysite.verizon.net/yellowspoon
The less utility can display text read from standard input. You can download 32-bit Windows binaries of the program, and Microsoft claims most programs designed for a computer running a 32-bit version of Windows will work on a computer running 64-bit versions of Windows.
You can simulate list.com file browsing and viewing features with vifm and less.
They are both freely available for windows.
After vifm installation just customize the "vi command" in the configuration file, and replace it with "less" (set vicmd = less \ -C)
You can also have a single pane display if you prefer so (with the "only" option).
Finally you can create a list.bat which calls vifm and changes the current directory on exit. This is the batch file content.
#echo off
for / f "delims =" %% i in ('vifm --choose-dir -% 1') do IF "%%i" NEQ "" (cd %%i)
More details in list.com lives on my blog

Resources