MsBuild calling Powershell. Passing array parameter?

986 views Asked by At

I have msbuild tasks that execs out to powershell modules. One of the ps module functions I call accepts an array type as a input parameter so I'm doing something like this:

<Exec Command="powershell -ExecutionPolicy unrestricted -command &quot;&amp; {Import-Module $(MyPowerShellModule); $(TargetFunction) -AnArray %40(&apos;OneArrayItem&apos;)}" ContinueOnError="ErrorAndContinue" />

What I'd like to do is be able to define a native msbuild property to some value, e.g.,

<PSArrayValues>OneArrayItem;TwoArrayItem;ThreeArrayItem</PSArrayValues>

and essentially can be parsed in such a way that my original target would wind up looking like:

<Exec Command="powershell -ExecutionPolicy unrestricted -command &quot;&amp; {Import-Module $(MyPowerShellModule); $(TargetFunction) -AnArray %40(&apos;OneArrayItem&apos,&apos;TwoArrayItem&apos,&apos;ThreeArrayItem&apos;)}" ContinueOnError="ErrorAndContinue" />

What approach(es) may be used for this?

1

There are 1 answers

0
Keith Hill On

You need to use MSBuild's item list flattening feature. Normally that would separate items in an item group with ; but you can change that to a , like so @(PSArrayValues, ',')/ Here is a test MSBuild project file that demonstrates this:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" 
         DefaultTargets="Test" 
         ToolsVersion="4.0">

  <Target Name="Test">
    <PropertyGroup>
      <TargetFunction>Foo</TargetFunction>
    </PropertyGroup>
    <ItemGroup>
      <PSArrayValues Include="OneArrayItem"/>
      <PSArrayValues Include="TwoArrayItem"/>
      <PSArrayValues Include="ThreeArrayItem"/>
    </ItemGroup>

    <Message Text="powershell -ExecutionPolicy unrestricted -command &quot;&amp; {Import-Module $(MyPowerShellModule); $(TargetFunction) -AnArray @(PSArrayValues, ',')}&quot;" 
             Importance="High" />
  </Target>
</Project>

This outputs:

29> msbuild .\test.proj
Microsoft (R) Build Engine version 14.0.22823.1
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 6/23/2015 1:44:12 PM.
Project "C:\Users\hillr\test.proj" on node 1 (default targets).
Test:
  powershell -ExecutionPolicy unrestricted -command "& {Import-Module ; Foo -AnArray OneArrayItem,TwoArrayI
  tem,ThreeArrayItem}"
Done Building Project "C:\Users\hillr\test.proj" (default targets).

Also note that your Exec command was missing the ending double quote after the last }.

Build succeeded.
    0 Warning(s)
    0 Error(s)