Find PID of conhost.exe process for the current CMD window - windows

I want to create a doskey command that closes the current CMD console window, without affecting any other open CMD console windows.
It has to work even when cmd.exe has been run (manually or by batch file) within that window. Ordinarily I would just use the exit command, but this does not close the window if other instances of cmd.exe have been run within that window.
I therefore decided to create a 'close' command that would always close the current window regardless of what had been run inside it. I chose the PID method of window detection (to avoid issues of windows with identical titles) and then used taskkill with /F and /T switches to kill the process. It worked fine, but it had the same problem as using the standard 'exit' command.
I ran tasklist and realised that the PID of the current CMD window changes whenever cmd.exe is run within it (you can see the multiple instances of cmd.exe listed, even though no new window has been opened) so using cmd.exe PID is not a usable method. However, each window does have its own conhost.exe process associated with it (regardless of the number of cmd instances) so killing the comhost process seems to be the best way to achieve what I want.
I tried it manually and it works exactly as I wanted.
Open one cmd console window, then run cmd.exe a couple of times within that window.
Open a second cmd console window, run cmd.exe a few times in that second window.
Use tasklist to find the PID of the conhost process for the window you
want to close.
Manually run:    taskkill /PID <PID of conhost process> /F   to kill the
selected conhost.
The above immediately closes the specified console window (and all of its related cmd.exe instances) while leaving the other console window alone.
I therefore just need to replicate the above process in a batch file so that I can use my doskey command to call that instead of my existing cmd PID checking code.
This is this code that I am using for current cmd PID detection (which I found online). I don't understand it (I'm a code newbie) but it works perfectly.
I then looked for method to determine the conhost PID based on the exiting cmd.exe PID of the current window, but I couldn't find anything except for this, which did not work (and which also caused various other problems with unrelated existing commands in my batch file).
Maybe there is an much simpler way of achieving my goal, but if killing conhost is the way to go then it seems to me that a modified version of the code below (to make it find the current conhost PID instead of the current cmd PID) would be the answer, because works reliably in a batch file very few lines of code.
set T=%TEMP%\sthUnique.tmp
wmic process where (Name="WMIC.exe" AND CommandLine LIKE "%%%TIME%%%") get ParentProcessId /value | find "ParentProcessId" >%T%
set /P A=<%T%
set PID=%A:~16%

Related

How to close a file using Shell?

I have a file opened named "C/Users/Desktop/textfile.txt". How do I close this using a shell script? I have tried taskkill, shutdown, "exec 1>&-" and others. Since I am new to shell, I am unable to figure out how to make it work.
textfile.txt is a non-executable file. That means you can't 'run' it, or 'kill' it. However, you can delete it - that is if some other process is not holding a lock on it.
If you want to release the lock, you have to first find the process that is holding a handle to this file, kill that process, and then the OS will let you delete the file.
From shell (command line), you can use this tool handle (https://learn.microsoft.com/en-us/sysinternals/downloads/handle) to identify which process is holding your handle. Once you get the pid (process id) from that tool, you can use taskkill to terminate that process and release the lock on that file.
c:\Program Files\SysinternalsSuite>handle.exe | findstr /i "c:/users/desktop/textfile.txt"
All said, you want to be careful when you terminate processes abruptly like this. The process won't get a chance to clean up behind itself.

Windows 8.1 batch file - closing separate command window

I'm trying to run a batch file that will close a different cmd window. I know I can do this:
TASKKILL /IM "myapplication.exe" /F
But whilst this does (obviously) kill the task, it doesn't close the cmd window myapplication.exe was running in. I cannot edit myapplication.exe or I would put an 'exit' on the last line.
Any help would be much appreciated.
Well, if your program was started from cmd, then obviously cmd is still running even if you kill or exit that application. To kill cmd as well you can apply the same command to a different program (in a quite obvious way).
However, this will also stop your batch file for equally obvious reasons.
Is there a particular need to run myapplication from cmd?

Keep Windows command window open

I'm running a command through the Windows shell- an existing command window (cmd.exe). When I execute the command, the window closes, even though it's a freestanding window not tied to the command.
How can I keep the window open to see the output?
You can't simply start a child cmd session because it'll share same window and if your custom tool actively closes its window (I wonder why) then it'll close your console and output will disappear.
There isn't much you can do if a program want to close console window but you can at least save its output to a file (to be inspected later with type). If you're working with that console and you don't want to close it then you can use start cmd to execute it in a new console window. Like this:
start cmd /c tool -args ^> output.txt
tool output will be available in output.txt after it finished.
It appears that the executable is closing the command window. Here is what you could try, may work. open a command shell. In the shell issue "cmd" and open another command shell. Run your executable in the newly opened command shell. You nested cmd will be exited, but you may still be able to see some of the output of your executable.

cmd.exe doesn't terminate when using a .bat file

[Context: I'm trying to create a shortcut to a .bat file with a relative "Start in" path as roughly described here and here.]
cmd.exe supports the /c switch. According to the documentation, this should cause it to "carry out the command and then terminate."
But the switch seems to be ignored when the command is a .bat file.
For example, if you create a shortcut with the following Target (to a normal, non-bat command):
C:\Windows\System32\cmd.exe /c "START /d C:\temp\ notepad.exe test.txt"
Everything works as expected: Notepad opens and the console (shell) disappears. But if you replace the command above with a .bat file instead, like so:
C:\Windows\System32\cmd.exe /c "START /d C:\temp\ C:\test.bat"
(where test.bat contains only "notepad.exe test.txt") Notepad opens as before but the console sticks around like an unwanted friend. Why? And more to the point, How do I make it go away?
UPDATE: I know I can use wscript, as in this solution, but then I lose the option of having a custom icon (I'm stuck with the default .vbs icon).
The start command begins a new process for the batch file. The original cmd.exe then terminates, but leaves the new process, which hangs around because it's waiting for notepad.exe to terminate.
Change your bat file contents to:
start "" notepad.exe test.txt
Then your batch file will not wait for notepad to exit before continuing execution.
Another thing to try:
C:\Windows\System32\cmd.exe /c "START /d C:\temp\ C:\test.bat & exit"
The nuclear option would be to write a small program in the (compiled) language of your choice that launches the .bat file and then exits. Then you can give it a custom icon, and make it do whatever you like.
You might also take a look at Autoit from http://autoitscript.com as an alternative to batch. - the Run() command can do this kind of thing with better predictability. Since it makes an executable you can link this from a shortcut directly. You can also do a whole lot more of course, like run as a different user, insert delays or handle errors, that are hard to do with batch.
You don't need the full kit, just the Aut2EXE folder from the download will do.
BTW, build your exes without UPX compression as that leads to AV false positives.
I'm a little late but here is the answer.
The documentation for start states:
Syntax
START "title" [/D path] [options] "command" [parameters]
If command is an internal cmd command or a batch file then the command
processor is run with the /K switch to cmd.exe. This means that the
window will remain after the command has been run.
If start is used to execute a batch file, the opened cmd instance wont close.
You could also use call instead.
call C:\test.bat

How do I launch a program from command line without opening a new cmd window?

I'm trying to programmatically execute an external file from cmd using this command:
START "filepath"
Where "filepath" is the path of my file. It opens fine but it also open a new command prompt window.
So, which is the right command for opening an external program without opening a new window?
In Windows 7+ the first quotations will be the title to the cmd window to open the program:
start "title" "C:\path\program.exe"
Formatting your command like the above will temporarily open a cmd window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.
Add /B, as documented in the command-line help for start:
C:\>start /?
Starts a separate window to run a specified program or command.
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/NODE <NUMA node>] [/AFFINITY <hex affinity mask>] [/WAIT] [/B]
[command/program] [parameters]
"title" Title to display in window title bar.
path Starting directory.
B Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application.
Just remove the double quote, this works in Windows 7:
start C:\ProgramFiles\folderName\app.exe
If you want to maximize the window, try this:
start /MAX C:\ProgramFiles\folderName\app.exe
Your command START "filepath" will start a command prompt and change the command prompt title to filepath.
Try to run start /? in windows command prompt and you will get more info.
I think if you closed a program
taskkill /f /im "winamp.exe"
//....(winamp.exe is example)...
end, so
if you want to start a program that you can use
start "" /normal winamp.exe
(/norma,/max/min are that process value cpu)
ALSO
start "filepath"
if you want command line without openning an new window
you write that
start /b "filepath"
/B is Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application.
If you're doing it via CMD as you say, then you can just enter the command like so:
path\to\your.exe
which will open it within the same window. For example in C++:
system("path\\to\\your.exe"); // Double backslash for escaping
will open your.exe in the current CMD window. Likewise to start with a new window, just go for:
system("start path\\to\\your.exe");
If you go for the first option, you would have to clear your screen unless you wanted to have the command to open your.exe on the screen still.
You can use the call command...
Type: call /?
Usage: call [drive:][path]filename [batch-parameters]
For example call "Example File/Input File/My Program.bat" [This is also capable with calling files that have a .exe, .cmd, .txt, etc.
NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!
Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...
I got it working from qkzhu but instead of using MAX change it to MIN and window will close super fast.
#echo off
cd "C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin"
:: Title not needed:
start /MIN mysqld.exe
exit
20190907
OS: Win 10
I'm making an exe in c++, for some reason usting START make my program fail.
So, just use quotes:
"c:\folder\program.exe"
It's easier and safer to use the explorer.exe to start files/executeables, it is also opening files with the associated program and runs executables directly, if you execute:
start "" "%windir%\explorer.exe" "C:\Path\To\some.pdf"
If *.PDF files are not associated with any program. This works similar to a double-click and triggers the "open with program" dialog.
start "" "%windir%\explorer.exe" "%windir%\system32\calc.exe"
Will bring up the calculator.
start "" "%windir%\explorer.exe" "C:\pagefile.sys"
Will bring up a warning like: You are trying to open a system file (*.sys)... choose a programm...
Important
explorer.exe always requires the full path to the executable/file, not the relative path.
If you want to use relative paths, use
start "" "%windir%\explorer.exe" "relative\file.pdf","C:\dir\"
Security related
Using start "" "some\file.dat" will try to execute the file as binary file and start it, if possible. This can end in security related issues.
You can test it by creating a copy of cmd.exe calling it dummy.dat and start it using start dummy.dat
1-Open you folder that contains your application in the File Explorer.
2-Press SHIFT and Right Click in White Space.
3-Click on "Open command window here".
4-Run your application. (you can type some of the first characters of application name and press Up Arrow Key OR Down Arrow Key)

Resources