简体   繁体   English

cmd.exe /k 开关

[英]cmd.exe /k switch

I am trying to switch to a directory using cmd and then execute a batch file我正在尝试使用 cmd 切换到目录,然后执行批处理文件

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.虽然第一行 (cmd /k) 似乎运行正常,但第二个命令从未运行。 I am using Vista as the OS我使用 Vista 作为操作系统

正确的语法是:

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

ssg already posted correct answer. ssg 已经发布了正确答案。 I would only add /d switch to cd command (eg. cd /d drive:\\directory ).我只会将 /d 开关添加到cd命令(例如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.这可确保命令在当前目录与您要 cd 到的目录位于不同驱动器上的情况下起作用。

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 `在 PowerShell 中,您需要使用反引号 ` 来转义引号

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.这将在cmd执行正确的命令,即用引号括起来的路径应该可以工作。

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.上面的示例命令将初始化 MSVC 开发人员命令提示符并返回到 PowerShell,继承环境并授予对 MSVC 工具的访问权限。

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.您可以在 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.据我了解,该命令作为"cd "c:\\myfolder" & startbatch.bat"传递给 cmd ,然后将其分解为cd "c:\\myfolder" & startbatch.bat ,此时剩余的" "将路径作为字符串处理。

You can also use && , |您也可以使用&& , | and |||| depending on what you want to achieve.取决于你想要达到的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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