PowerShell访问SharePoint Online遇传输连接强制关闭问题求助
核心原因
7000条属于大列表范畴,默认单次请求拉取数据量过大触发SPO系统限制,导致连接被强制断开;另外也可能是TLS版本过低、请求超时设置不足或未正确分页导致的问题。
安全可行的解决方案(按优先级排序)
1. 启用分页+限制单页数据量
这是最稳妥的方案,通过拆分请求避免单次拉取过多数据,同时只获取需要的字段减少传输负载:
# 连接SharePoint Online Connect-PnPOnline -Url "https://你的租户.sharepoint.com/sites/你的站点" -Interactive # 定义参数 $libraryName = "目标文档库名称" $outputPath = "C:\temp\文件访问记录.csv" $pageSize = 800 # 建议500-1000,平衡效率与稳定性 $allItems = @() $currentPage = 1 do { try { # 分页拉取指定字段 $items = Get-PnPListItem -List $libraryName -PageSize $pageSize -Page $currentPage -Fields "FileLeafRef","LastAccessedDate" $allItems += $items Write-Host "已拉取第$currentPage页,累计$($allItems.Count)条数据" $currentPage++ } catch { Write-Warning "第$currentPage页拉取失败:$($_.Exception.Message)" # 单次失败后重试2次 $retry = 0 while ($retry -lt 2) { Start-Sleep -Seconds 6 try { $items = Get-PnPListItem -List $libraryName -PageSize $pageSize -Page $currentPage -Fields "FileLeafRef","LastAccessedDate" $allItems += $items Write-Host "重试第$($retry+1)次成功,已拉取第$currentPage页" $currentPage++ break } catch { $retry++ Write-Warning "重试第$($retry)次仍失败" } } if ($retry -eq 2) { Write-Error "第$currentPage页放弃,继续下一页" $currentPage++ } } } while ($items.Count -eq $pageSize) # 导出为CSV $allItems | Select-Object ` @{Name="文件名";Expression={$_.FieldValues.FileLeafRef}},` @{Name="最后访问日期";Expression={$_.FieldValues.LastAccessedDate}} ` | Export-Csv -Path $outputPath -NoTypeInformation -Encoding UTF8 Write-Host "导出完成,文件路径:$outputPath"
要点:
- 仅拉取
FileLeafRef(文件名)和LastAccessedDate字段,大幅减少数据传输量 - 分页逻辑自动终止,直到拉完所有数据
- 内置局部重试,比全局
-RetryCount更精准
2. 强制使用TLS 1.2
部分环境默认TLS版本过低,SPO会拒绝连接,执行命令前先设置(仅临时生效,关闭PowerShell后自动恢复):
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
3. 延长连接超时时间
连接时增加超时参数,避免因大请求耗时过长被断开:
Connect-PnPOnline -Url "https://你的租户.sharepoint.com/sites/你的站点" -Interactive -TimeoutSec 300
4. 改用Get-PnPFile(仅需文件属性时)
如果不需要列表项的其他属性,直接用文件专用命令更高效稳定:
Connect-PnPOnline -Url "https://你的租户.sharepoint.com/sites/你的站点" -Interactive $libraryName = "目标文档库名称" $outputPath = "C:\temp\文件访问记录.csv" Get-PnPFile -FolderSiteRelativeUrl $libraryName -Recurse -IncludeFileProperties | Select-Object Name, @{Name="最后访问日期";Expression={$_.Properties.LastAccessedDate}} | Export-Csv -Path $outputPath -NoTypeInformation -Encoding UTF8
新手操作注意事项
- 先在测试站点/小文档库验证命令,确认正常再操作生产环境
- 导出路径选择本地有写入权限的文件夹(比如
C:\temp) - 执行时关闭占用网络的程序,保证网络稳定
内容的提问来源于stack exchange,提问作者Playstation_waifu
相关产品推荐
相关产品推荐

