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

PowerShell脚本无法批量删除CSV中用户,仅单条目可删除求助

修复SharePoint批量删除用户对应文件的PowerShell脚本

你的脚本在CSV包含多用户条目时失效,核心原因是循环中错误引用了整个CSV集合的users字段,而非当前循环处理的单个用户条目。以下是修复后的完整代码及关键修改说明:

修复后的脚本

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
$CSVPath = "D:\Temp\userss.csv"
$CSVFile = Import-CSV $CSVPath
$web = Get-SPWeb -Identity https://................./
$DocLibsName = "Bilder der websitesammlung"
$folder = $web.Folders[$DocLibsName].SubFolders

foreach($entry in $CSVFile)
{
    Write-Host "正在获取用户..." -ForegroundColor Blue
    # 引用当前循环项的users字段,而非整个CSV集合
    $user = $entry.users
    # 筛选匹配当前用户的文件
    $items = $folder.Files | Where-Object {$_.Title -eq $user}

    # 先判断是否找到匹配文件,避免空值报错
    if ($items)
    {
        $items.Delete()
        Write-Host "$user 已删除" -ForegroundColor DarkGreen
    }
    else { 
        Write-Host "$user 未找到" -ForegroundColor DarkRed 
    }
}

Write-Host "处理完成" -ForegroundColor Green
# 释放SPWeb对象,避免内存泄漏
$web.Dispose()

关键修改点

  • 循环变量名从$Files改为$entry:语义更清晰,避免和文件对象混淆
  • 核心修复:将$user = $CSVFile.users改为$user = $entry.users,确保每次循环取当前行的用户值,而非整个CSV的所有用户集合
  • 调整判断逻辑:直接检查$items是否存在,而非$items.Title -contains $user,避免$items为空时触发报错
  • 增加$web.Dispose():手动释放SharePoint的SPWeb对象,防止内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:40:41