简体   繁体   中英

cmd.exe /k switch

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

eg

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

正确的语法是:

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

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.

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 , ie 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.

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

或者,为什么不运行cmd /kc:\\myfolder\\startbatch.bat ,并在 .bat 文件中执行cd c:\\myfolder

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

Example:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM