从PowerShell运行cmd.exe

时间:2015-02-18 09:29:51

标签: powershell cmd

我正在尝试使用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

然后这会运行,但当然对我没用。这是问题的第二个参数。我试过的其他事情。我怎么能让它运行?

$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

1 个答案:

答案 0 :(得分:10)

运行此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