Home > other >  Windows batch file to open new window and issue command
Windows batch file to open new window and issue command

Time:08-16

I have a batch file, mybatch.cmd, which successfully opens 3 command line windows:

start "CMD LINE 1" CD C:\dir1
start "CMD LINE 2" CD C:\dir2
start "CMD LINE 3" CD C:\dir3

But I want to expand this to issue a subsequent command (e.g., "echo test") within each new window. So I tried this:

start "CMD LINE 1" CD C:\dir1 echo test
start "CMD LINE 2" CD C:\dir2 echo test
start "CMD LINE 3" CD C:\dir3 echo test

But that gives me The system cannot find the path specified. Any suggestions?

I realize this question seems like a duplicate of this. But none of those answers are working for me.

Specifically, neither /c or /k seem to do the trick - though they do work when I remove the CD part of my command. It's almost like the CD is incompatible with the /c and /k.

Solution:

Fixed by modifying each line to 1) add cmd.exe; 2) put commands in quotes, separated by &:

start "CMD LINE 1" cmd.exe /D /K "CD C:\SOURCE & echo test"

Note it's probably best to specify the full path to cmd.exe, as shown in the answer below, but I left that off for simplicity (and it works).

CodePudding user response:

To do what you're talking about, you need to specify the Command Prompt application executable cmd.exe:

You can perform the command used in your examples just like this:

@Start "CMD LINE 1" /D "C:\dir1" %SystemRoot%\System32\cmd.exe /D /K
@Start "CMD LINE 2" /D "C:\dir2" %SystemRoot%\System32\cmd.exe /D /K
@Start "CMD LINE 3" /D "C:\dir3" %SystemRoot%\System32\cmd.exe /D /K

If you didn't really want to just open the prompts with a specific directory as your current directory, then the following methodology may be better for you:

@Start "CMD LINE 1" %SystemRoot%\System32\cmd.exe /D /K "CD /D "C:\dir1""
@Start "CMD LINE 2" %SystemRoot%\System32\cmd.exe /D /K "CD /D "C:\dir2""
@Start "CMD LINE 3" %SystemRoot%\System32\cmd.exe /D /K "CD /D "C:\dir3""

Obviously in the case of not really wanting to change directory, but to run another command or commands, (linked together using ampersands), you would change CD /D "C:\dirN" with the actual command, but please ensure that you do not remove the enclosing doublequotes for the /K option.

  • Related