When we use lookup fields in SharePoint, we are able to configure the field to show additional fields from the list that is used as the target of the lookup as shown in the following image:

Technically SharePoint will create two fields for this lookup column (or more, depending how many additional columns are selected). When we want to create such a field using the Office 365 PnP PowerShell extensions, we can use the Add-PnPFieldFromXml cmdlet. For each field, we need one xml-definition as shown in the following example:

Main field

<Field 
	Type="Lookup" 
	ID="{890a17aa-8062-4e25-a5f5-d14357b8a704}" 
	Name="MyColor" 
	DisplayName="MyColor" 
	StaticName="MyColor" 
	List="{6a49e685-22d1-4f2f-bca3-eb01efd69613}" 
	WebId="81297a18-0e89-4c75-90f1-91981ee15d5d" 
	SourceID="{81297a18-0e89-4c75-90f1-91981ee15d5d}" 
	ShowField="Title" 
	UnlimitedLengthInDocumentLibrary="FALSE" 
	Required="FALSE" 
	EnforceUniqueValues="FALSE" 
	Group="Tester" 
/>

Secondary field

<Field 
	Type="Lookup" 
	ID="{b2ae0377-9b77-44c2-8b0f-765dda207fbc}" 
	Name="MyColor_x003A_Value" 
	DisplayName="MyColor:Value" 
	StaticName="MyColor_x003a_Value" 
	List="{6a49e685-22d1-4f2f-bca3-eb01efd69613}" 
	WebId="81297a18-0e89-4c75-90f1-91981ee15d5d" 
	SourceID="{81297a18-0e89-4c75-90f1-91981ee15d5d}" 
	FieldRef="890a17aa-8062-4e25-a5f5-d14357b8a704" 
	ShowField="Value" 
	ReadOnly="TRUE" 
	UnlimitedLengthInDocumentLibrary="FALSE" 
	Group="Tester" 
/>

There is a relationship between the attributes in the xml-definitions, as shown in the following image (ignore and do not use the attribute “Version”, as you can see it in the image):

To create the fields, we can use the following script:


function AddFieldToWeb([string]$Path)
{
	$content = Get-Content $Path

	$string = [string]$content

	Add-PnPFieldFromXml -FieldXml $string 
}

AddFieldToWeb .\Fields\MyColor.xml
AddFieldToWeb .\Fields\MyColor.Value.xml

Remember, the xml-definition includes the guid of the list and the web. So it’s necessary to patch these xml-definitions, before they could be used in a deployment scenario.

Advertisements