The PowerShell extensions from the Office 365 Patterns and Practices provide a cmdlet to create a new field in a list (or in the site columns) from an xml. That could perfectly be used to create a lookup field. The xml file should look similar to this (in the example this file is named LookupField.xml):

<Field 
	ID="{e83578ab-f63e-4c46-bae5-b0e211dd5003}"
	DisplayName="Company"
	Name="Company"
	StaticName="Company"
	Type="Lookup"
	Required="FALSE"
	EnforceUniqueValues="FALSE"
	List="Companies"
	ShowField="Title" 
/>

But, to be able to create the field with this xml file, we need to replace the name of the list in the list attribute with the Id of the list. This could be done with the following script (PatchLookupFieldXml.ps1) that returns the modified xml from the file:

param (
    [string]$LookupFieldXml
)

$content = Get-Content $LookupFieldXml
$content = [string]$content

$xmlDoc = New-Object System.Xml.XmlDocument
$xmlDoc.LoadXml($content)

[System.Xml.XmlElement]$root = $xmlDoc.DocumentElement

$listName = $root.List

if ($listName -ne $null -and $listName -ne "")
{
    $list = Get-SPOList -Identity $listName

    $listId = $list.Id

    $root.List = "{$listid}"

    Write-Output $xmlDoc.InnerXml
}
else
{
    Write-Output $null
}

Now we can use these two simple lines to add our lookup field:

$fieldXml = .\PatchLookupFieldXml.ps1 -LookupFieldXml C:\Temp\LookupField.xml
Add-SPOFieldFromXml -FieldXml $fieldXml -List "Documents"

Done.

Advertisements