Who Got The Func Part 3: Generating a GUID in MSBuild
I’m in a bit of a Property Function mood at the moment with our builds. We generate a GUID within our builds for an Id required in one of our config file and some more for our WiX installers. There’s two ways to create GUIDs. Which one you use really depends on what version of MSBuild you are using.
MSBuild 4
Property Functions were only made available in MSBuild 4.
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="4.0" DefaultTargets="GenerateNewGuid">
<Target Name="GenerateNewGuid">
<PropertyGroup>
<NewGuid>$([System.Guid]::NewGuid())</NewGuid>
</PropertyGroup>
<Message Text="Guid: $(NewGuid)" />
<BuildStep Name="GenerateGuid"
Message="Generating Guid $(NewGuid) for foo.xml"
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildURI)"
Condition="'$(IsDesktopBuild)' != 'true'">
<Output TaskParameter="Id" PropertyName="GenerateGuidId" />
</BuildStep>
<BuildStep Id="$(GenerateGuidId)"
Name="GenerateGuid"
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildURI)"
Condition="'$(IsDesktopBuild)' != 'true'"
Status="Succeeded" />
</Target>
</Project>
< MSBuild 4
Prior to MSBuild 4 the best way was to use the script task from MSBuild Community Tasks. In the script below I have placed it in the $(MSBuildExtensionsPath) on the build server, which is typically “C:\Program Files (x86)\MSBuild”.
<pre><?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="4.0" DefaultTargets="GenerateNewGuid">
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
<Target Name="GenerateNewGuid">
<PropertyGroup>
<GenerateGuid>
<![CDATA[
public static string ScriptMain() {
return System.Guid.NewGuid().ToString().ToUpper();
}
]]>
</GenerateGuid>
</PropertyGroup>
<Script Language="C#" Code="$(GenerateGuid)">
<Output TaskParameter="ReturnValue" PropertyName="NewGuid" />
</Script>
<Message Text="Guid: $(NewGuid)" />
<BuildStep Name="GenerateGuid"
Message="Generating Guid $(NewGuid) for foo.xml"
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildURI)"
Condition="'$(IsDesktopBuild)' != 'true'">
<Output TaskParameter="Id" PropertyName="GenerateGuidId" />
</BuildStep>
<BuildStep Id="$(GenerateGuidId)"
Name="GenerateGuid"
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildURI)"
Condition="'$(IsDesktopBuild)' != 'true'"
Status="Succeeded" />
</Target>
</Project>