如何使用 & 从 PowerShell 调用 MSBuild操作员? [英] How to invoke MSBuild from PowerShell using & operator?

查看:46
本文介绍了如何使用 & 从 PowerShell 调用 MSBuild操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've just tested this on PowerShell v1.0. Setup is as follows:

 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 的解决方法.

Please explain. I'm more interested in why the & syntax isn't working, than an MSBuild-specific workaround.

推荐答案

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

The issues you are seeing results from PowerShell parsing arguments. In the first example, when PowerShell sees $a it passes it as a single parameter msbuild. We can see this using the echoargs utility from PSCX:.

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" 作为命令名称,它不是一个有效的命令名称.

The second example is even worse because you are telling powershell to invoke "$echoargs $a" as the command name and it isn't a valid command name.

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

The third line works because CMD.exe gets the expanded form of "$echoargs $a" as a single argument which is parses and executes:

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

You have a couple of options here. First I do it this way:

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

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

The other option is to use Invoke-Expression like so:

PS> Invoke-Expression "$msbuild $a"

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

In general I try to be very careful with Invoke-Expression particularly if any part of the string that gets invoked is provided by the user.

这篇关于如何使用 &amp; 从 PowerShell 调用 MSBuild操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆