Adding Lookup Field to a SharePoint list via PowerShell (SharePoint/PNP)
-
08-02-2021 - |
Domanda
I am trying to create a lookup field via Sharpoint PNP PowerShell module.
And here is my script:
$URL = "https://testing.sharepoint.com/sites/sitename"
Connect-PnPOnline -url $URL -Credential credentialname
$targetlistname = "users" ## Name of the target list
$sourcelistname = "testlist" ## Name of the list which contains the lookup field
$sourcefieldname = "Title" ## Name of the lookup column
$lookupfielddisplayname = "JustTesting" ## Name of the new column
$lookupfieldinternalname = "justtesting" ## Name of the internal name of the new column
Add-PnPField -List $targetlistname -DisplayName $lookupfielddisplayname -InternalName $lookupfieldinternalname -Type Lookup -LookUpList $sourcelistname -LookUpValue $sourcefieldname
I would like to achieve this:
Can someone help me with the correct syntax?
Soluzione
Currently, Add-PnPField command still not support "LookupList" parameter, please refer the opening issue here:
Question: Adding a lookup field with Add-PnPField #1518
A workaround is to add the field with schema like this:
$xml = '<Field Type="Lookup" DisplayName="testlookup" Required="FALSE" EnforceUniqueValues="FALSE" List="{2cefea32-3396-4a9f-9117-753d110a6d4e}" ShowField="Title" UnlimitedLengthInDocumentLibrary="FA
LSE" RelationshipDeleteBehavior="None" ID="{c7da3702-965c-4cdf-b6ca-48801af6860a}" SourceID="{ffb78df3-46ea-4b1a-b596-b01adfaa2692}" StaticName="testlookup" Name="testlookup"/>'
Add-PnPFieldFromXml -List "MyList11" -FieldXml $xml
In the schema above, List is the target list Guid, showField is the target field name, SourceID is the Source List Guid.
Altri suggerimenti
Currently Add-PnPField
doesn not support parameterized creation of Lookup columns. You can use the below code (tried and tested).
$URL = "https://testing.sharepoint.com/sites/sitename"
Connect-PnPOnline -url $URL -Credential credentialname
$targetlistname = "users" ## Name of the target list
$sourcelistID = "List ID here" ## ID of the source list (click on list settings and in url you get it's ID)
$sourcefieldname = "Title" ## Name of the lookup column
$lookupfielddisplayname = "JustTesting" ## Name of the new column
$lookupfieldinternalname = "justtesting" ## Name of the internal name of the new column
$ctx = Get-PnPContext
$lookupField = Add-PnPField -List $targetlistname -DisplayName $lookupfielddisplayname -InternalName $lookupfieldinternalname -Type Lookup -AddToDefaultView
$lookupField = $lookupField.TypedObject
$lookupField.LookupList = $sourcelistID
$lookupField.LookupField = $sourcefieldname
$lookupField.update()
$ctx.ExecuteQuery()
Thanks
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange