ซิงค์ข้อมูลรายการ SharePoint จากไฟล์ CSV โดยใช้ PowerShell
ความต้องการ: เรามีรายการ SharePoint ที่มีหลายฟิลด์เพื่อรวบรวมความเชี่ยวชาญของบุคลากรทั่วทั้งองค์กร รายการนี้มีช่องเฉพาะที่เรียกว่า "ทีม" และจะต้องอัปเดตจากไฟล์ CSV ที่มีมากกว่า 100 แถว ใช่ มุมมองแผ่นข้อมูลสามารถช่วยได้ แต่ปัญหาคือ: ค่าฟิลด์ทีมที่จะอัปเดตในรายการที่ตรงกับฟิลด์ "ชื่อบัญชี" ของรายการ SharePoint และไฟล์ CSV
วิธีแก้ปัญหา:
มาเขียนสคริปต์ PowerShell เพื่อเลือกแถวที่ตรงกันจากไฟล์ CSV ไปยังรายการ SharePoint แล้วอัปเดต
สคริปต์ PowerShell เพื่อซิงค์ข้อมูลรายการ SharePoint จากไฟล์ 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
}
}
}
}
ฉันได้เพิ่มการตรวจสอบเพิ่มเติม เช่น การตรวจสอบว่าค่าฟิลด์ทีมปัจจุบันว่างเปล่าตามความต้องการทางธุรกิจหรือไม่
