代码之家  ›  专栏  ›  技术社区  ›  Peter Seale

如何使用&运算符从PowerShell调用MSBuild?

  •  37
  • Peter Seale  · 技术社区  · 17 年前

    我刚刚在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特定的解决方法。

    4 回复  |  直到 12 年前
        1
  •  47
  •   Peter Seale    17 年前

    啊。

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

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

        2
  •  33
  •   Keith Hill    17 年前

    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”作为命令名,但它不是有效的命令名。

    你有几个选择。首先,我这样做:

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

    PS> Invoke-Expression "$msbuild $a"
    

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

        3
  •  4
  •   Janus Troelsen    10 年前

    您也可以尝试使用免费 Invoke-MsBuild powershell script/module

        4
  •  0
  •   espumita    5 年前

    这对我来说很有效:

    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'
    
    推荐文章