【问题标题】:How to invoke MSBuild from PowerShell using & operator?如何使用 & 运算符从 PowerShell 调用 MSBuild?
【发布时间】:2009-05-15 15:15:32
【问题描述】:

我刚刚在 PowerShell v1.0 上对此进行了测试。设置如下:

 Id CommandLine
 -- -----------
  1 $msbuild = "C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe"
  4 $a = "C:\some\project\or\other\src\Solution.sln /target:Clean /target:Build"

.

此行失败并显示不直观的错误消息:

 Id CommandLine
 -- -----------
  5 & $msbuild $a

.

此行失败,因为 & 期望第一个参数是命令本身。

 Id CommandLine
 -- -----------
 10 & "$msbuild $a"

.

这条线有效:

 Id CommandLine
 -- -----------
 16 cmd /c "$msbuild $a"

.

请解释一下。我对 & 语法为什么不起作用比特定于 MSBuild 的解决方法更感兴趣。

【问题讨论】:

  • 我建议使用Invoke-MSBuild 等辅助cmdlet,而不是直接调用MSBuild。

标签: powershell


【解决方案1】:

呃。

$collectionOfArgs = @("C:\some\project\or\other\src\Solution.sln", 
    "/target:Clean", "/target:Build")
& $msbuild $collectionOfArgs

这行得通。 & 接受参数集合,因此您必须将包含多个参数的字符串拆分为字符串参数集合。

【讨论】:

  • 太棒了...为我工作了由于日志记录而产生的参数日志列表。
  • 很好的解决方案!加上@keith-hill 提供的解释,这完全有道理。
  • #blessYou 这让我很兴奋。
  • 为避免错误“msbuild.exe 未被识别为 cmdlet 的名称”,msbuild 路径不得用双引号引起来。这是 $msbuild 变量的工作声明:$msbuild = "$MSBUILD_PATH\msbuild.exe"
【解决方案2】:

您看到的问题来自 PowerShell 解析参数。在第一个示例中,当 PowerShell 看到 $a 时,它会将其作为单个参数 msbuild 传递。我们可以使用PSCX: 中的 echoargs 实用程序看到这一点。

PS> $a = "C:\some\project\or\other\src\Solution.sln /target:Clean /target:Build"
PS> & echoargs $a
Arg 0 is <C:\some\project\or\other\src\Solution.sln /target:Clean /target:Build>

第二个例子更糟糕,因为你告诉 powershell 调用“$echoargs $a”作为命令名,它不是一个有效的命令名。

第三行有效,因为 CMD.exe 将 "$echoargs $a" 的扩展形式作为解析和执行的单个参数:

这里有几个选项。首先我这样做:

PS> & $msbuild C:\some\project\or\other\src\Solution.sln `
    /target:Clean /target:Build

另一种选择是像这样使用 Invoke-Expression:

PS> Invoke-Expression "$msbuild $a"

一般来说,我会非常小心地使用 Invoke-Expression,特别是如果被调用的字符串的任何部分是由用户提供的。

【讨论】:

  • 这对我不起作用。我猜字符串由于某种原因没有正确解析。下面@PeterSeale 的解决方案对我有用
【解决方案3】:

您也可以尝试使用免费的Invoke-MsBuild powershell script/module。这实际上为您提供了一个 Invoke-MsBuild PowerShell cmdlet,您可以调用它而不是尝试自己手动调用 msbuild.exe。

【讨论】:

    【解决方案4】:

    这对我很有效:

    PS> cmd.exe /c 'C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe' /target:Clean /target:Build 'C:\some\project\or\other\src\Solution.sln'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      相关资源
      最近更新 更多