PowerShell 清空 SharePoint Online 列表数据

  前言

  最近,在做项目的测试,然后,好多好多垃圾数据。

  正文

  1.还是先上执行成功的截图,PowerShell命令非常巴适,如下图:

image

  2.这是详细的命令,大家可以品一下,如下图:

<#
.SYNOPSIS
PowerShell 7专用 - 批量删除列表项(支持过滤条件)
.DESCRIPTION
遍历列表项并删除,可添加过滤条件,适合精准删除数据
#>

# -------------------------- 可配置变量 --------------------------
$siteUrl = "https://linyus.sharepoint.com/sites/Develop"  # 站点地址
$listName = "产品管理列表"                                      # 目标列表名称
$batchSize = 100                                                # 批量删除大小(避免请求超限)
# 可选:添加过滤条件(如只删除"是否上架"为false的项)
$filterCondition = ""  # 示例:"IsOnShelf eq false"

# -------------------------- 执行逻辑 --------------------------
# 加载PnP模块
if (-not (Get-Module -ListAvailable -Name PnP.PowerShell)) {
    Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
    Install-Module -Name PnP.PowerShell -Force -AllowClobber -Scope CurrentUser
}
Import-Module PnP.PowerShell -DisableNameChecking -Force

try {
    # 连接站点
    Connect-PnPOnline -Url $siteUrl -UseWebLogin -ErrorAction Stop
    Write-Host "✅ 成功连接到站点: $siteUrl" -ForegroundColor Green

    # 检查列表是否存在
    $list = Get-PnPList -Identity $listName -ErrorAction SilentlyContinue
    if (-not $list) {
        throw "列表 '$listName' 不存在,请检查名称是否正确"
    }

    # 获取列表项(支持过滤条件)
    Write-Host "📊 正在获取列表 '$listName' 中的数据..." -ForegroundColor Cyan
    $listItems = Get-PnPListItem -List $listName -PageSize $batchSize -ErrorAction Stop #-Filter $filterCondition 
    $totalCount = $listItems.Count

    if ($totalCount -eq 0) {
        Write-Host "ℹ️ 列表 '$listName' 中无数据,无需删除" -ForegroundColor Blue
        exit 0
    }

    Write-Host "⚠️ 共获取到 $totalCount 条数据,即将批量删除" -ForegroundColor Yellow

    # 批量删除列表项
    $deletedCount = 0
    foreach ($item in $listItems) {
        Remove-PnPListItem -List $listName -Identity $item.Id -Force -Recycle:$true -ErrorAction SilentlyContinue
        $deletedCount++
        # 进度提示(每删除10条显示一次)
        if ($deletedCount % 10 -eq 0) {
            Write-Host "🔄 已删除 $deletedCount/$totalCount 条数据" -ForegroundColor Cyan
        }
    }

    Write-Host "✅ 批量删除完成!共删除 $deletedCount 条数据(数据已放入回收站)" -ForegroundColor Green
}
catch {
    Write-Host "❌ 操作失败: $($_.Exception.Message)" -ForegroundColor Red
}
finally {
    # 断开连接
    if (Get-PnPConnection) {
        Disconnect-PnPOnline -ErrorAction SilentlyContinue
    }
}

  结束语

  其实,没啥好说的,用就是了

posted @ 2026-03-01 23:01  霖雨  阅读(24)  评论(0)    收藏  举报