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”.

&lt;pre&gt;&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;Project xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;
ToolsVersion=&quot;4.0&quot; DefaultTargets=&quot;GenerateNewGuid&quot;&gt;
&lt;Import Project=&quot;$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets&quot;/&gt;

&lt;Target Name=&quot;GenerateNewGuid&quot;&gt;

&lt;PropertyGroup&gt;
&lt;GenerateGuid&gt;
&lt;![CDATA[
public static string ScriptMain() {
return System.Guid.NewGuid().ToString().ToUpper();
}
]]&gt;
&lt;/GenerateGuid&gt;
&lt;/PropertyGroup&gt;

&lt;Script Language=&quot;C#&quot; Code=&quot;$(GenerateGuid)&quot;&gt;
&lt;Output TaskParameter=&quot;ReturnValue&quot; PropertyName=&quot;NewGuid&quot; /&gt;
&lt;/Script&gt;

&lt;Message Text=&quot;Guid: $(NewGuid)&quot; /&gt;

&lt;BuildStep Name=&quot;GenerateGuid&quot;
Message=&quot;Generating Guid $(NewGuid) for foo.xml&quot;
TeamFoundationServerUrl=&quot;$(TeamFoundationServerUrl)&quot;
BuildUri=&quot;$(BuildURI)&quot;
Condition=&quot;'$(IsDesktopBuild)' != 'true'&quot;&gt;
&lt;Output TaskParameter=&quot;Id&quot; PropertyName=&quot;GenerateGuidId&quot; /&gt;
&lt;/BuildStep&gt;

&lt;BuildStep Id=&quot;$(GenerateGuidId)&quot;
Name=&quot;GenerateGuid&quot;
TeamFoundationServerUrl=&quot;$(TeamFoundationServerUrl)&quot;
BuildUri=&quot;$(BuildURI)&quot;
Condition=&quot;'$(IsDesktopBuild)' != 'true'&quot;
Status=&quot;Succeeded&quot; /&gt;

&lt;/Target&gt;

&lt;/Project&gt;