我想在Windows CMD控制台中运行两个命令。

在Linux中我会这样做

touch thisfile ; ls -lstrh

在Windows上是怎么做的呢?


当前回答

如果你想创建一个cmd快捷方式(例如在你的桌面上),添加/k参数(/k表示保持,/c将关闭窗口):

cmd /k echo hello && cd c:\ && cd Windows

其他回答

文档中的一段话:

来源:微软,Windows XP专业产品文档,命令shell概述 另外:Windows CMD命令的A-Z索引

Using multiple commands and conditional processing symbols You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol. For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful. You can use the special characters listed in the following table to pass multiple commands. & [...] command1 & command2 Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command. && [...] command1 && command2 Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully. || [...] command1 || command2 Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero). ( ) [...] (command1 & command2) Use to group or nest multiple commands. ; or , command1 parameter1;parameter2 Use to separate command parameters.

你可以使用call来克服环境变量被太快求值的问题。

set A=Hello & call echo %A%

当在同一行上运行多个命令时,可以使用许多处理符号,在某些情况下可能导致处理重定向,在其他情况下可能改变输出,或者导致失败。一个重要的例子是将操作变量的命令放在同一行。

@echo off
setlocal enabledelayedexpansion
set count=0
set "count=1" & echo %count% !count!

0 1

正如您在上面的例子中看到的,当使用变量的命令被放在同一行时,您必须使用延迟展开来更新变量值。如果你的变量被索引了,使用CALL命令和%%修饰符来更新它在同一行的值:

set "i=5" & set "arg!i!=MyFile!i!" & call echo path!i!=%temp%\%%arg!i!%%

path5=C:\Users\UserName\AppData\Local\Temp\MyFile5

&是Bash中等价的;&&是Bash中的&&(只在前一个没有导致错误时才运行命令)。

我试图创建批处理文件启动提升cmd,并使其运行2个单独的命令。 当我使用&或&&字符时,我遇到了一个问题。例如,这是我的批处理文件中的文本:

powershell.exe -Command "Start-Process cmd \"/k echo hello && call cd C:\ \" -Verb RunAs"

我得到解析错误:

经过几次猜测,我发现,如果你用“&&”这样的引号包围&&,它是有效的:

powershell.exe -Command "Start-Process cmd \"/k echo hello "&&" call cd C:\ \" -Verb RunAs"

结果如下:

也许这能帮到别人:)