简体   繁体   中英

Import Values in lookup Columns in Sharepoint Online using CSOM powershell

I am trying to import values in lookup columns, i have country parent list and a child list which has lookup column as Region, am trying below code but it does not seem work at all, i think i am wrong with the syntax may be

###### Add all functions here##########
foreach($row in $CSVLocation)
{
$item["ABC_x0020_DEF"]=$row.'ABC DEF'

 ##############
#Get the Lookup Item from Parent List
 $LookupItem = $country.GetItems | Where-Object { $row.'Region' -eq $row["Region"]}

if($LookupItem -ne $null)
{
$RegionLookup = New-Object Microsoft.Sharepoint.SPFieldLookupValue($LookupItem.ID,$row.Region)

#Set the Lookup field value
$item["Region"] = $RegionLookup
}
}
}
 ##############
     $item.Update();
     $spoCtx.ExecuteQuery();

First of all, you are not using CSOM object but server side object. It is not Microsoft.SharePoint.SPFieldLookupValue but it is Microsoft.SharePoint.Client.FieldLookupValue .

Create function for finding the right item in items collection.

function Get-Item($Items, $ColumnName, $Value)
{
    foreach ($item in $Items.GetEnumerator())
    {
        if ($item[$ColumnName] -eq $Value)
        {
            return $item
        }
    }

    return $null
}

You are using the method GetItems() incorrectly. It should leverage the CamlQuery object.

$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$LookupItems = $country.GetItems($query)

# Execute query and get items from SharePoint
$spoCtx.Load($LookupItems)
$spoCtx.ExecuteQuery()

You don't have to create this FieldLookupValue object, just set the lookup item ID.

#Get the Lookup Item from Parent List items collection
$LookupItem = Get-Item -Items $LookupItems -ColumnName "Region" -Value $row.'Region'

if($LookupItem -ne $null)
{
    #Set the Lookup field value
    $item["Region"] = $LookupItem.Id
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM