Start a process in a new window from a batch file - windows

I have written a batch file (.bat) in windows. I want to execute a particular process in a new window. How do I do this?
Example
a.py -s 3 -l 5
b.py -k 0 -> I want to start this in a new window and let the original batch file continue
C:\program.exe
...
....

Use the start command:
start foo.py
or
start "" "c:\path with spaces\foo.py"

start "title" "C:\path\to\file.exe"
I would highly recommend inserting a title so that you can call that title later via the TASKKILL command if needed.
TASKKILL /im title

The solutions below are for calling multiple files in the same window; this question has been answered already so I am just adding my 2 cents.
If you are working with a master batch file that calls multiple other batch files, you would use the "call" command. These aren't processes, though.
Within the other batch files you can call the "start" command to start them in separate windows.
master.bat
call myCoolBatchFile1.bat
call myCoolBatchFile2.bat
call myCoolBatchFile3.bat
If you are using Windows Powershell, you can use the Start-Process command.
myPowershell.ps1:
#silent install java from java exe.
$javaLogLocation = "[my log path here]"
$javaFileName = "[javaInstaller file name here].exe"
$process = "$javaFileName"
$args = "/lang=1033 /s /L $javaLogLocation"
Start-Process $process -ArgumentList $args -Wait
For more info on the start command and its usages, as well as other scripting tech:
https://ss64.com/nt/start.html

As per the requirement, we can follow up like this. As I was doing an automation work for my office purpose. So I need to create a process for a certain time, & after that I have to kill the service/ process.
So What I did,
For start a process:
**`start "API" C:\Python27\python.exe`**
Then I tried with my all other works & tasks. After that I need to kill that process. So That I did,
**`taskkill /F /IM python.exe`**
After killing the process, outcome ran smoothly.

Related

use root cmd window to execute commands in new cmd window

i'm trying to make a batch script for running my Java files. I've found out that there is no way to prevent auto-closure of a batch script(except using pause keyword, tho it just waits for key press). I've also discovered that starting a new window will cause only main windows to close, not the new one too so i want a way that the command SET /P file=Java file: is executed in the new window(I got the new window by using the start keyword. Is there any way to accomplish this without downloading other softwares? this is the code i came up with yet:
cd "C:\Users\DEVDHRITI\Desktop\Files&Folders\HMMMMM\programs\java programmes"
set /P file=Java file to execute:
java %file%^.jar
start
I guess you're looking for that :
cd "C:\Users\DEVDHRITI\Desktop\Files&Folders\HMMMMM\programs\java programmes"
start cmd /V:ON /K "#set /P "file=Java file to execute: " && java -jar !file!^.jar"
EDIT: Using expansion with /V and use of /K instead of /C to keep the cmd windows open.
Explanations : To launch a console process in another windows and keep it open after the end of this process console we launch another cmd process with the start command. We use /V:ON to use delayed expansion by default, meaning modified variables (like the one we prompt, %file%) will be expanded on the fly with ! (so !file! instead of %file%). We use /K to tell to this cmd process to not close when provided commands end. To this cmd process, we provide the following commands :
#set /P "file=Java file to execute: "
This one will ask for the jar filename (without extension) to launch.
The # means "do not echo the command itself on the console stdout" for a nice display.
java -jar %file%^.jar
This one launch the java interpreter (JVM) with the filename of a jar file to execute through the -jar parameter, filename build from the previous prompt and the .jar extension. The ^ here escapes the ., it seems not useful here but maybe your script/env requires it.
We link the both commands with && which means : _if left command from && is successful (it exits with ERRORLEVEL 0) then execute the right command from &&.

.cmd file on Win10 - How to "multi thread" to have actions fire concurrently? [duplicate]

Say, if I have
foo.exe
bar.exe
baz.exe
How do I run all of them from a batch file asynchronously, i.e. without waiting for the previous program to stop?
Using the START command to run each program should get you what you need:
START "title" [/D path] [options] "command" [parameters]
Every START invocation runs the command given in its parameter and returns immediately, unless executed with a /WAIT switch.
That applies to command-line apps. Apps without command line return immediately anyway, so to be sure, if you want to run all asynchronously, use START.
Combining a couple of the previous answers, you could try start /b cmd /c foo.exe.
For a trivial example, if you wanted to print out the versions of java/groovy/grails/gradle, you could do this in a batch file:
#start /b cmd /c java -version
#start /b cmd /c gradle -version
#start /b cmd /c groovy -version
#start /b cmd /c grails -version
If you have something like Process Explorer (Sysinternals), you will see a few child cmd.exe processes each with a java process (as per the above commands). The output will print to the screen in whatever order they finish.
start /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
cmd /c : Carries out the command specified by string and then terminates
You can use the start command to spawn background processes without launching new windows:
start /b foo.exe
The new process will not be interruptable with CTRL-C; you can kill it only with CTRL-BREAK (or by closing the window, or via Task Manager.)
Create a batch file with the following lines:
start foo.exe
start bar.exe
start baz.exe
The start command runs your command in a new window, so all 3 commands would run asynchronously.
Use the START command:
start [programPath]
If the path to the program contains spaces remember to add quotes. In this case you also need to provide a title for the opening console window
start "[title]" "[program path]"
If you need to provide arguments append them at the end (outside the command quotes)
start "[title]" "[program path]" [list of command args]
Use the /b option to avoid opening a new console window (but in that case you cannot interrupt the application using CTRL-C
There's a third (and potentially much easier) option. If you want to spin up multiple instances of a single program, using a Unix-style command processor like Xargs or GNU Parallel can make that a fairly straightforward process.
There's a win32 Xargs clone called PPX2 that makes this fairly straightforward.
For instance, if you wanted to transcode a directory of video files, you could run the command:
dir /b *.mpg |ppx2 -P 4 -I {} -L 1 ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"
Picking this apart, dir /b *.mpg grabs a list of .mpg files in my current directory, the | operator pipes this list into ppx2, which then builds a series of commands to be executed in parallel; 4 at a time, as specified here by the -P 4 operator. The -L 1 operator tells ppx2 to only send one line of our directory listing to ffmpeg at a time.
After that, you just write your command line (ffmpeg.exe -i "{}" -quality:v 1 "{}.mp4"), and {} gets automatically substituted for each line of your directory listing.
It's not universally applicable to every case, but is a whole lot easier than using the batch file workarounds detailed above. Of course, if you're not dealing with a list of files, you could also pipe the contents of a textfile or any other program into the input of pxx2.
I could not get anything to work I ended up just using powershell to start bat scripts .. sometimes even start cmd /c does not work not sure why .. I even tried stuff like start cmd /c notepad & exit
start-Process "c:\BACKUP\PRIVATE\MobaXterm_Portable\MobaXterm_Portable.bat" -WindowStyle Hidden

Execute a URL from a command line without opening a browser in windows

So I'm putting together a batch file to run at startup that executes a small number of processes, one of them is to execute a reboot of a certain program at the end of the set of processes. I've been searching ways how to do this in the command line in windows but I need to be able to do this without opening a browser. What I need is to execute the reboot in the following url without opening a browser at all.
http://192.168.1.100/cgi-bin/reboot
Everything that I've tried has opened a new browser window. I don't want to have to download anything to get this going in windows if that's possible. Thanks for any suggestions.
You know how sometimes the answer to the question you ask is not necessarily the answer you need? I have a vague suspicion this might be one of those times.
If this is a Windows machine you're trying to reboot, you can reboot it remotely without needing to use a CGI script served by the remote host. If the account you're logged in with on the triggering PC also has privileges on the remote PC, you can trigger the reboot with the shutdown command.
shutdown /m \\remotePC /r /t 0
Do shutdown /? in a cmd console for more info. Or if you must authenticate, you can use wmic instead.
wmic /node:remotePC /user:remotePCadmin /password:remotePCpass process call create "shutdown -r -t 0"
In case I was mistaken, here's the answer to the question you asked. The fastest way to execute a remote CGI script would be to use an XMLHTTPRequest with Windows Script Host (VBScript or JScript). Here's an example.
#if (#CodeSection == #Batch) #then
#echo off & setlocal
set "URL=http://192.168.1.100/cgi-bin/reboot"
cscript /nologo /e:jscript "%~f0" "%URL%"
goto :EOF
#end // end batch / begin JScript chimera
var x = WSH.CreateObject("Microsoft.XMLHTTP");
x.open("GET",WSH.Arguments(0),true);
x.setRequestHeader('User-Agent','XMLHTTP/1.0');
x.send('');
while (x.readyState != 4) WSH.Sleep(50);
For what it's worth, you can also parse x.responseText as needed. You can scrape it as flat text, or even evaluate it as a hierarchical DOM object. This answer demonstrates such parsing. And if you just can't get enough, here are more examples.
If you'd rather have something simpler at the expense of efficiency, you can invoke a PowerShell command.
#echo off & setlocal
set "URL=http://192.168.1.100/cgi-bin/reboot"
powershell "ipmo BitsTransfer; Start-BitsTransfer \"%URL%\" \"%temp%\a\""
del /q "%temp%\a"
goto :EOF
You could probably alternatively use Invoke-WebRequest to avoid the temporary file, but Invoke-WebRequest requires PowerShell version 3 or newer. Start-BitsTransfer works with PowerShell version 2, so it should work on more computers. One might also use the [System.Net]::WebRequest .NET class, but it gets a little complicated constructing all the objects needed to proceed beyond fetching the HTTP headers to having the web server serve the web page. If you're curious, it looks something like this:
powershell "[void](new-object IO.StreamReader([Net.WebRequest]::Create(\"%URL%\").GetResponse().GetResponseStream())).ReadToEnd()"
Not exactly what I'd call simple. In hybrid format for easier readability:
<# : batch portion
#echo off & setlocal
set "URL=http://192.168.1.100/cgi-bin/reboot"
powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF
: end batch / begin PowerShell hybrid chimera #>
$request = [Net.WebRequest]::Create($env:URL)
$response = $request.GetResponse()
$stream = $response.GetResponseStream()
$reader = new-object IO.StreamReader($stream)
[void]$reader.ReadToEnd()
In any case, any PowerShell solution will be a second or two slower than the JScript solution near the top of this answer. powershell.exe takes a second or two to load (indeed, several seconds if it's not been loaded since Windows was last rebooted); whereas cscript.exe fires nearly instantly.
If you cannot download anything, then Windows PowerShell is the best option. You can call it from a PS script file, or directly from the command line in a batch file:
powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://192.168.1.100/cgi-bin/reboot"
You can also consider Curl for that type of process. There is no equivalent in Windows, so it will require a download.
curl http://192.168.1.100/cgi-bin/reboot
Curl will not open a browser window, and has great command line options (See curl -help), and will return error codes for batch file error handling.
I don't think Windows comes with that feature.
Try making a VBscript that will open the browser Windows but will not display anything maybe.
To process URL response direct, from Win CMD:
powershell "Invoke-WebRequest -Uri <url>"
To save server response to file:
powershell "Invoke-WebRequest -Uri <url> -outfile <file.ext>"
.NET solution; from Win CMD:
powershell "[System.Net.Webclient]::new().DownloadString(\"<URL>\")"

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

Windows bat - calling programs for different cmd

I wonder if I can execute some programs for different cmd's using .bat file. Look at this example .bat file:
start cmd //number one
start cmd //number two
ping localhost //call in number one
ping 192.168.1.100 //call in number two
I know that both will be executed in main window (the window where I started .bat file), but I think its easy to get the idea. This code is quite useless, but its just an example.
Thanx for all replies.
EDIT: I know about /k switch, but any way to do this not using it?
You can start your commands with
start cmd /k ping localhost
start cmd /k ping 192.168.1.100
That will start two new command line prompts, run the ping command in each one seperately and both windows and the /k switch will make them stay open afterwards.
Ah, posted before your edit ... ;) The only way to interact with a shell is giving it a command to be executed when it starts. There is no way to have interaction between shells
CMD.EXE has two parameters, /C and /K, which let you specify a command to execute. /C closes the window when the command is finished, whereas /K keeps it running.
If you want to excute multiple commands within a single window, you'll need to concatenate them with && or similar - this will require quoting; CMD /? will tell you all the details on that - or you can have it start a batch file containing the commands.

Resources