You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PnP PowerShell上传CSV到SharePoint列表如何跳过已存在条目

PnP PowerShell 避免上传重复条目的调整方案

核心逻辑

我们以资产编号(Asset Number)作为唯一重复判定字段(你现有脚本中该字段会存入SharePoint列表的Title列),每次新增前先校验该条目是否已存在,仅不存在时执行新增操作。

修改后的完整脚本

#Parameters
$SiteUrl = "{site}"
$ListName = "iPhone"
$CSVPath = "C:\Users\{user}\Documents\PowerShell\Upload SharePoint items from CSV\iphoneexport.csv"

#Get the CSV file contents
$CSVData = Import-CsV -Path $CSVPath

#Connect to site
Connect-PnPOnline $SiteUrl -Interactive

#Iterate through each Row in the CSV and import data to SharePoint Online List
ForEach ($Row in $CSVData)
{
    $assetNumber = $Row.'Asset Number'
    Write-Host "正在处理条目 $assetNumber"
    
    # 查询列表中是否已存在当前资产编号的条目
    $existingItem = Get-PnPListItem -List $ListName -Query "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>$assetNumber</Value></Eq></Where></Query></View>"
    
    if ($null -eq $existingItem) {
        Write-Host "条目不存在,正在新增"
        #Add List Items - Map with Internal Names of the Fields!
        Add-PnPListItem -List $ListName -Values @{
            "Title" = $assetNumber
            "User" = $Row.User
        }
    } else {
        Write-Host "条目已存在,跳过上传"
    }
}

大数据量场景优化建议

如果你的列表数据量超过5000条,建议提前将列表中所有现有资产编号一次性读取到本地数组中,避免循环内反复调用查询接口,大幅提升执行效率,同时也能规避CSV自身存在重复行的问题:

#Parameters
$SiteUrl = "{site}"
$ListName = "iPhone"
$CSVPath = "C:\Users\{user}\Documents\PowerShell\Upload SharePoint items from CSV\iphoneexport.csv"

#Get the CSV file contents
$CSVData = Import-CsV -Path $CSVPath

#Connect to site
Connect-PnPOnline $SiteUrl -Interactive

# 提前读取所有现有条目的资产编号到缓存
$existingAssets = (Get-PnPListItem -List $ListName -Fields "Title").Title | Select-Object -Unique

ForEach ($Row in $CSVData)
{
    $assetNumber = $Row.'Asset Number'
    Write-Host "正在处理条目 $assetNumber"
    if ($existingAssets -notcontains $assetNumber) {
        Write-Host "条目不存在,正在新增"
        Add-PnPListItem -List $ListName -Values @{
            "Title" = $assetNumber
            "User" = $Row.User
        }
        # 新增后把编号加入缓存,避免CSV自身重复的情况
        $existingAssets += $assetNumber
    } else {
        Write-Host "条目已存在,跳过上传"
    }
}

内容的提问来源于stack exchange,提问作者alexthannah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:06:04