0

I am using SharePoint 2013, I need to create a lookup field through PowerShell.

I tried this code but is not working:

$SiteUrl = "http://mySite" 
$WebObj = Get-SPWeb -identity $SiteUrl 
$myCustomList = $WebObj.Lists["newList"]
$ParentList=$WebObj.Lists.item("listTarget")
$myCustomList.Fields.AddLookup("NewLookupField",$ParentList.id,$false)  
$SPChildListLookupField = $myCustomList.Fields[$_.NameField]
$SPChildListLookupField.LookupField = $ParentList.Fields["fieldTarget"]

I want to lookup to a list on a custom field (not the default Title)

3 Answers 3

2

I solved updating the field.

$SiteUrl = "http://mySite" 
$WebObj = Get-SPWeb -identity $SiteUrl 
$myCustomList = $WebObj.Lists["newList"]
$ParentList=$WebObj.Lists.item("listTarget")
$myCustomList.Fields.AddLookup("NewLookupField",$ParentList.id,$false)  
$SPChildListLookupField = $myCustomList.Fields[$_.NameField]
$SPChildListLookupField.LookupField = $ParentList.Fields["fieldTarget"]

//Added this line
$SPChildListLookupField.Update()
0

Try to change this line.

$myCustomList = $WebObj.Lists.item("newList")
2
  • Thanks, I tried but it is not working :/ Commented Apr 29, 2014 at 15:43
  • Does it throw an error? Is the field created at all? Commented Apr 29, 2014 at 16:11
0

Resolved:

Use below script to add Lookup field:

Provide the List Id for the field xml property 'List'

$Field_LookupList = $RootWeb.Lists.GetByTitle('DemoListForLookup')
$clientContext.Load($Field_LookupList)
$clientContext.ExecuteQuery()

$Field_LookupList_Id = $Field_LookupList.Id


$fieldXml="<Field Type='Lookup'  DisplayName='"+ $Field_DisplayName +"' Required='"+$Field_Required+"'  StaticName='"+$Field_InternalName+"' Name='"+$Field_InternalName+"' List='"+$Field_LookupList_Id+"' ShowField='"+$Field_LookupListFields+"'/>" 
$spoList.Fields.AddFieldAsXml($fieldXml,$true,[Microsoft.SharePoint.Client.AddFieldOptions]::AddFieldInternalNameHint)
$spoList.Update()
$clientContext.ExecuteQuery()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.