使用PowerShell从带有空格的目录运行EXE文件

13

我试图从C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ Common7 \ IDE 运行MSTest.exe。此外,我正在将当前目录中的所有程序集作为单独的/ testcontainer参数进行设置。 我无法在没有PowerShell投诉的情况下解决此问题。

$CurrentDirectory = [IO.Directory]::GetCurrentDirectory()

$MSTestCall = '"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"'

foreach($file in Get-ChildItem $CurrentDirectory) 
{
    if($file.name -match "\S+test\S?.dll$" )
    {
        $MSTestArguments += "/TestContainer:" + $file + " "
    }
}

$MSTestArguments += " /resultsFile:out.trx"
$MSTestArguments += " /testsettings:C:\someDirectory\local64.testsettings"

Invoke-Expression "$MSTestCall $MSTestArguments"

这段代码给出的错误是:

Invoke-Expression:在“/”运算符右侧必须提供值表达式。

当我尝试在名称中没有空格的目录中调用mstest.exe时,我不会遇到此错误(不需要额外的")。

当我尝试使用&时,

&$MSTestCall $MSTestArguments

е®ѓе°†$MSTestArgumentsдҢњдёғеҚ•дёҒеЏ‚ж•°дә йЂ’пәЊдҢ†MSTestз«‹еҚіе°†е…¶дёұеәѓгЂ‚жњ‰д»Ђд№€е»ғи®®еђ—пәџ


1
这里的额外引号是不必要的(实际上在这种情况下会导致问题)- $MSTestCall = '"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"'。一旦你把 "foo bar.exe" 放入变量 $foo 中,那么它就包含了该字符串及其中的空格。调用 & $foo 就像预期的那样工作,即执行由变量 $foo 中的字符串命名的命令。 - Keith Hill
2
关于字符串和正则表达式的另一个注意事项。通常情况下,除非我需要在正则表达式中指定PowerShell变量,否则我使用单引号字符串,这样PowerShell就不会“解释”像$1这样的东西。此外,您指定了.dll,我怀疑您想要的是\ .dll。整个字符串都要用单引号括起来 - '\S+test\S?\.dll$' - Keith Hill
2个回答

24

我建议您使用一个参数数组和运算符&。请参见我的回答中的示例: 从PowerShell执行存储在变量中的命令

在这种情况下,代码应该类似于:

$MSTestCall = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"
$MSTestArguments = @('/resultsFile:out.trx', '/testsettings:C:\someDirectory\local64.testsettings')

foreach($file in Get-ChildItem $CurrentDirectory)  
{ 
    if($file.name -match "\S+test\S?.dll$" ) 
    { 
        $MSTestArguments += "/TestContainer:" + $file
    } 
} 

& $MSTestCall $MSTestArguments

非常好。这是一个很棒的解决方案。谢谢。 - user467384

-1

这个可以工作吗?

$MSTestCall = @'"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\MSTest.exe"'@

这样做不行,因为在开头的 here string 序列 @' 后面必须要开始一个新行。 - Keith Hill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接