cmd.exe /k switch

2019-02-04 02:49发布

问题:

I am trying to switch to a directory using cmd and then execute a batch file

e.g.

cmd /k cd "C:\myfolder"
startbatch.bat

I have also tried (without success)

cmd cd /k cd "C:\myfolder" | startbatch.bat

Although the first line (cmd /k) seems to run ok, but the second command is never run. I am using Vista as the OS

回答1:

Correct syntax is:

cmd /k "cd c:\myfolder & startbatch.bat"


回答2:

ssg already posted correct answer. I would only add /d switch to cd command (eg. cd /d drive:\directory). This ensures the command works in case current directory is on different drive than the directory you want to cd to.



回答3:

cmd cd /k "cd C:\myfolder; startbatch.bat"

or, why don't you run cmd /k c:\myfolder\startbatch.bat, and do cd c:\myfolder in the .bat file?



回答4:

You can use & or && as commands separator in Windows.

Example:

cmd cd /K "cd C:\myfolder && startbatch.bat"


回答5:

I give this as an answer because I saw this question in a comment and cannot comment yet.

cmd /k "cd c:\myfolder & startbatch.bat"

works, and if you have spaces:

cmd /k "cd "c:\myfolder" & startbatch.bat"

As I understand it, the command is passed to cmd as "cd "c:\myfolder" & startbatch.bat", which is then broken down into cd "c:\myfolder" & startbatch.bat at which point the remaining " " takes care of the path as string.

You can also use &&, | and || depending on what you want to achieve.



回答6:

I can't see an answer addressing this, so if anyone needs to access a directory that has space in its name, you can add additional quotes, for example

cmd.exe /K """C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat"" & powershell.exe"

From PowerShell you need to escape the quotes using the backquote `

cmd.exe /K "`"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat`" & powershell.exe"

Notice the escaped quotes

`"

inside the path string:

"`"C:\my path\`""

This will execute the proper command in cmd, i.e. the path surrounded with quotes which should work.

The example command above will initialise the MSVC developer command prompt and go back to PowerShell, inheriting the environment and giving access to the MSVC tools.