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)

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")
  • Thanks, I tried but it is not working :/ – Nk SP Apr 29 '14 at 15:43
  • Does it throw an error? Is the field created at all? – Michael Colbs Apr 29 '14 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, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.