Sincronizar datos de lista de SharePoint desde un archivo CSV usando PowerShell
Requisito: Tenemos una lista de SharePoint con varios campos para capturar la experiencia de las personas de toda la organización. Esta lista tiene un campo particular llamado "Equipo" y debe actualizarse desde un archivo CSV de más de 100 filas. Sí, la vista Hoja de datos puede ayudar, pero el problema es: El valor del campo Equipo se actualizará en los elementos que coincidan con el campo "Nombre de cuenta" de la lista de SharePoint y el archivo CSV.
Solución:
Escribamos un script de PowerShell para seleccionar la fila coincidente del archivo CSV en la lista de SharePoint y luego actualícela.
Script de PowerShell para sincronizar datos de la lista de SharePoint desde un archivo CSV:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Read the CSV file
$CSVData = Import-CSV -path "C:\Expertdata.csv"
#Get the Web
$web = Get-SPWeb -identity "https://portal.crescent.com"
#Get the Target List
$list = $web.Lists["ExpertProfiles"]
$TeamsLookupList = $web.Lists["Teams"]
#Iterate through each Row in the CSV
foreach ($row in $CSVData)
{
#Get the matching Row from Experts List in SharePoint
$item = $list.Items | Where-Object {$_["AccountName"] -eq $row.AccountName}
if($item -ne $null)
{
Write-Host "Found Matching User in the Experts List:"$row.AccountName
#If the CSV data has valid Team data
if( ( $row.Team -ne $null) -and ( $row.Team -ne [string]::Empty) )
{
#Get Team Field Value (Lookup column) from the Expert Item
$ExpertTeam = New-Object Microsoft.SharePoint.SPFieldLookupValue($Item["Team"])
#If the current Team Value is empty or Null
if ( ($ExpertTeam.LookupValue -eq $null) -or ( $ExpertTeam.LookupValue -eq [string]::Empty))
{
#Get the Team from Parent Lookup List
$LookupItem = $TeamsLookupList.Items | where {$_["Team"] -eq $row.Team} | Select-Object -First 1
$item["Team"] = $LookupItem.ID
$item.Update()
Write-Host "Updated Team in:"$row.AccountName -ForegroundColor Green
}
}
}
}
Agregué validaciones adicionales, como: Verificar si el valor del campo Equipo actual está vacío según los requisitos comerciales.
