运行 cmd.exe 来自 PowerShell

Run cmd.exe from PowerShell

我正在尝试 运行 使用 PowerShell 进行一些单元测试。我有一个(有点)有效的命令:

$output = & $vsTestPath $TestAssembly $logger $TestCaseFilter 2>&1

问题是标准输出流和标准错误流输出的顺序不正确——它们混淆了。一个解决方案(来自 here)是使用 cmd.exe,但我无法让它工作。我觉得我已经尝试了所有我能想到的。

这是我拥有的:

$vsTestPath = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"
$TestAssembly = "C:\IntegrationTesting\Test Application\Ads.Slms.IntegrationTesting.Web.Smartfill.dll"
$output = & cmd.exe /c $vsTestPath $TestAssembly 2`>`&1

最后一行不起作用。奇怪的是,如果我有

$output = & cmd.exe /c $vsTestPath 2`>`&1

然后这个运行s,不过当然对我没用。这是问题所在的第二个参数。我尝试过的其他事情。我怎样才能把它送到 运行?

$output = & cmd.exe /c $vsTestPath $TestAssembly 2`>`&1
$output = & cmd.exe /c $vsTestPath,$TestAssembly 2`>`&1
$output = & cmd.exe /c "$vsTestPath" $TestAssembly 2`>`&1
$output = & cmd.exe /c """$vsTestPath""" $TestAssembly 2`>`&1
$output = & cmd.exe /c "$vsTestPath" "$TestAssembly" 2`>`&1
$output = & cmd.exe /c """$vsTestPath""" """$TestAssembly""" 2`>`&1

当你 运行 这个 PowerShell 命令时,

& cmd.exe /c $vsTestPath $TestAssembly 2`>`&1

PowerShell 生成此命令行:

cmd.exe /c "C:\Program Files (x86)\BlaBlaBla.exe" "C:\IntegrationTesting\Test Application\BlaBlaBla.dll" 2>&1

PowerShell 将 $vsTestPath$TestAssembly 的值括在引号中,因为它们包含空格并且第一个字符本身不是引号。现在您必须了解 cmd 如何处理此命令行(请参阅 cmd /?):

If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:

    1.  If all of the following conditions are met, then quote characters
        on the command line are preserved:

        - no /S switch
        - exactly two quote characters
        - no special characters between the two quote characters,
          where special is one of: &<>()@^|
        - there are one or more whitespace characters between the
          two quote characters
        - the string between the two quote characters is the name
          of an executable file.

    2.  Otherwise, old behavior is to see if the first character is
        a quote character and if so, strip the leading character and
        remove the last quote character on the command line, preserving
        any text after the last quote character.

如您所见,我们有两个以上的引号,第一个字符是引号,因此 cmd 将从命令行中删除第一个和最后一个引号:

C:\Program Files (x86)\BlaBlaBla.exe" "C:\IntegrationTesting\Test Application\BlaBlaBla.dll 2>&1

现在你实际上开始 C:\Program 有一些参数,你很可能没有 C:\Program.exeC:\Program.cmd。解决方案:添加额外的引号以使 cmd 满意:

& cmd.exe /c `" $vsTestPath $TestAssembly 2`>`&1 `"
cmd.exe /c " "C:\Program Files (x86)\BlaBlaBla.exe" "C:\IntegrationTesting\Test Application\BlaBlaBla.dll" 2>&1 "
"C:\Program Files (x86)\BlaBlaBla.exe" "C:\IntegrationTesting\Test Application\BlaBlaBla.dll" 2>&1