请求创建PowerShell脚本:连接SharePoint文档库遍历文件夹生成带-PROD的CSV
这个PowerShell脚本可实现以下功能:
- 接收指定的SharePoint站点URL和文档库名称作为参数
- 遍历文档库内所有文件夹及子文件夹
- 查找所有CSV格式文件
- 读取原CSV内容并在原文件夹创建/更新附加"-PROD"后缀的新CSV文件
前置要求
- 安装PnP PowerShell模块:
Install-Module -Name PnP.PowerShell -Force -AllowClobber - 执行脚本的账号需具备目标SharePoint站点文档库的读写权限
使用方法
运行脚本时传入站点URL和文档库名称参数:
.\Process-SPOCSVFiles.ps1 -SiteUrl "https://yourtenant.sharepoint.com/sites/yoursite" -LibraryName "YourDocumentLibrary"
完整脚本
param( [Parameter(Mandatory=$true)] [string]$SiteUrl, [Parameter(Mandatory=$true)] [string]$LibraryName ) # 连接到SharePoint站点 Connect-PnPOnline -Url $SiteUrl -Interactive try { # 获取文档库内所有CSV文件(包含子文件夹) $csvFiles = Get-PnPListItem -List $LibraryName -Query "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='File_x0020_Type'/><Value Type='Text'>csv</Value></Eq></Where></Query></View>" if (-not $csvFiles) { Write-Host "未在文档库中找到任何CSV文件" -ForegroundColor Yellow exit } Write-Host "找到 $($csvFiles.Count) 个CSV文件,开始处理..." -ForegroundColor Green # 创建临时目录用于存放下载的文件 $tempDir = Join-Path -Path $env:TEMP -ChildPath "SPOCSVProcessing" if (-not (Test-Path $tempDir)) { New-Item -Path $tempDir -ItemType Directory | Out-Null } foreach ($file in $csvFiles) { $fileUrl = $file["FileRef"] $fileName = $file["FileLeafRef"] $folderPath = $fileUrl.Replace("/$fileName", "") # 生成新文件名 $newFileName = $fileName -replace "\.csv$", "-PROD.csv" $newFileUrl = "$folderPath/$newFileName" Write-Host "处理文件: $fileName" -ForegroundColor Cyan # 下载原文件到临时目录 $localFilePath = Join-Path -Path $tempDir -ChildPath $fileName Get-PnPFile -Url $fileUrl -Path $tempDir -FileName $fileName -AsFile -Force # 读取CSV内容(保留原格式) $csvContent = Get-Content -Path $localFilePath -Raw # 检查目标文件是否存在,存在则更新,不存在则创建 if (Get-PnPFile -Url $newFileUrl -ErrorAction SilentlyContinue) { # 更新现有文件 Set-PnPFile -Path $localFilePath -Url $newFileUrl -Checkout -CheckInComment "Updated via PowerShell script" -Force Write-Host "已更新文件: $newFileName" -ForegroundColor Green } else { # 上传新文件 Add-PnPFile -Path $localFilePath -Folder $folderPath -FileName $newFileName Write-Host "已创建文件: $newFileName" -ForegroundColor Green } } Write-Host "所有CSV文件处理完成" -ForegroundColor Green } catch { Write-Host "处理过程中发生错误: $_" -ForegroundColor Red } finally { # 断开连接并清理临时文件 Disconnect-PnPOnline if (Test-Path $tempDir) { Remove-Item -Path $tempDir -Recurse -Force } }
脚本说明
- 参数验证:强制要求传入
SiteUrl和LibraryName两个参数,确保脚本可以定位到目标文档库 - 递归遍历:使用
RecursiveAll视图查询所有子文件夹内的CSV文件 - 文件处理逻辑:先下载原文件到本地临时目录,读取内容后上传为带"-PROD"后缀的新文件,支持更新已存在的目标文件
- 错误处理:包含异常捕获机制,确保出错时能输出错误信息
- 资源清理:脚本执行完成后自动断开SharePoint连接并删除临时文件
内容的提问来源于stack exchange,提问作者Dheeraj Rao
相关产品推荐
相关产品推荐

