Creating Lookup field by Powershell

Hello everyone!

I am creating a Lookup field in a custom list by powershell. I did it with the following code:

$spWeb = Get-SPWeb -Identity $url
$list = $spWeb.Lists["TargetList"]
$ParentList = $spWeb.Lists["ParentList"] 
$list.Fields.AddLookup("LookupName",$ParentList.id,$true) 

This code creates the lookup field. Now I want to conifgure this lookup field to related with the field "Title" of the parent List, because in default it is pointed to the field "ID": 

$SPChildListLookupField = $list.Fields["LookupName"]
$SPChildListLookupField.LookupField = $ParentList.Fields["Title"].internalname
$SPChildListLookupField.Update()

$spWeb.Dispose()

The problem comes that when I check the lookup field it is still related to the field "ID" from the parent list... The code is in a .ps1 file. However, if I copy and paste directly the code to the SHP powershell console it works correctly and the lookup field is pointing to the field "Title" of the parent list.

Any idea on what could be the problem? Becuase I tryed and searched everything.

Thanks,

Luis.

 

January 28th, 2015 12:06pm

Hi,

According to your description, you might want to add a Lookup field to a list using PowerShell.

Please save the script below as a .ps1 file and execute it in your environment for a test:

if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
     Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$url = "http://yoursite"
$ParentListName = "List1"
$TargetListName = "List2"
$ParentFieldName = "Title"
$TargetFieldName = "LK1"
$listViewName = "All Items"

#Adding the field to the desired list 
$spWeb = Get-SPWeb -Identity $url
$targetList = $spWeb.Lists[$TargetListName]
$parentList = $spWeb.Lists[$ParentListName] 
$targetList.Fields.AddLookup($TargetFieldName,$parentList.id,$true) 
$SPChildListLookupField = $targetList.Fields[$TargetFieldName]
$SPChildListLookupField.LookupField = $parentList.Fields[$ParentFieldName].internalname
$SPChildListLookupField.Update() 

#Adding the field to the desired list view 
$view = $targetList.Views[$listViewName]             
$view.ViewFields.Add($TargetFieldName) 
$view.Update() 

$spWeb.Dispose()

Feel free to reply if there any progress.

Best regards
Free Windows Admin Tool Kit Click here and download it now
February 2nd, 2015 4:49am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics