使用 PowerShell 同步 CSV 文件中的 SharePoint 列表数据
要求:我们有一个包含多个字段的 SharePoint 列表,用于捕获组织范围内人员的专业知识。该列表有一个名为“团队”的特定字段,需要从 100 多行的 CSV 文件进行更新。是的,数据表视图可以提供帮助,但问题是:要在与 SharePoint 列表和 CSV 文件的“AccountName”字段匹配的项目上更新团队字段值。
解决方案:
让我们编写一个 PowerShell 脚本,从 CSV 文件中选择匹配的行到 SharePoint 列表,然后更新它。
用于从 CSV 文件同步 SharePoint 列表数据的 PowerShell 脚本:
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
}
}
}
}
我添加了额外的验证,例如:根据业务要求检查当前团队字段值是否为空。
