【问题标题】:Running an EXE file using PowerShell from a directory with spaces in it使用 PowerShell 从包含空格的目录运行 EXE 文件
【发布时间】:2010-10-05 22:48:43
【问题描述】:

我正在尝试从 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 会立即抛出该参数。有什么建议吗?

【问题讨论】:

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

标签: powershell spaces


【解决方案1】:

我建议您使用 array 参数和运算符 &。在此处查看我的答案中的示例:Executing a Command stored in a Variable from 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

【讨论】:

  • 优秀。这是一个很好的解决方案。谢谢。
【解决方案2】:

这行得通吗?

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

【讨论】:

  • 这行不通,因为您必须在此处打开字符串序列@' 后开始换行。
猜你喜欢
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 2011-10-22
  • 2010-12-13
  • 2017-02-23
  • 2018-07-08
相关资源
最近更新 更多