基于文档日期批量移动SharePoint Online文件的PowerShell脚本需求
前置准备
- 安装PnP PowerShell模块:
Install-Module -Name PnP.PowerShell -Force -AllowClobber - 确保你拥有目标SharePoint站点的编辑权限
完整脚本
# 配置参数 $siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite" # 替换为你的站点URL $libraryName = "Documents" # 替换为你的库名称 $sourceFolderPath = "00" # 源文件夹相对库的路径 # 月份与目标文件夹映射,可根据需要扩展 $monthFolders = @{ 1 = "January" 2 = "February" 3 = "March" } # 连接到SharePoint Online站点 Connect-PnPOnline -Url $siteUrl -Interactive # 获取源文件夹 $sourceFolder = Get-PnPFolder -Url "$libraryName/$sourceFolderPath" if (-not $sourceFolder) { Write-Error "源文件夹不存在,请检查路径配置" exit } # 分页获取源文件夹下所有文件(支持5000+大数量) $files = Get-PnPListItem -List $libraryName -FolderServerRelativeUrl $sourceFolder.ServerRelativeUrl -PageSize 500 foreach ($file in $files) { # 提取Document date属性值 $docDateStr = $file["Document date"] if (-not $docDateStr) { Write-Warning "文件 [$($file.FieldValues.FileLeafRef)] 未设置Document date属性,跳过" continue } # 解析日期(自动适配常见格式,若为特定格式需调整) $docDate = $null if (-not [DateTime]::TryParse($docDateStr, [ref]$docDate)) { Write-Warning "文件 [$($file.FieldValues.FileLeafRef)] 的Document date格式无效:$docDateStr,跳过" continue } # 匹配目标文件夹 $targetFolderName = $monthFolders[$docDate.Month] if (-not $targetFolderName) { Write-Warning "文件 [$($file.FieldValues.FileLeafRef)] 的月份[$($docDate.Month)]不在目标列表中,跳过" continue } # 检查并创建目标文件夹 $targetFolderPath = "$libraryName/$targetFolderName" $targetFolder = Get-PnPFolder -Url $targetFolderPath -ErrorAction SilentlyContinue if (-not $targetFolder) { Write-Host "创建目标文件夹: $targetFolderName" $targetFolder = New-PnPFolder -Name $targetFolderName -Folder $libraryName } # 执行文件移动 try { Write-Host "正在移动: $($file.FieldValues.FileLeafRef) -> $targetFolderName" Move-PnPFile -SourceUrl $file.FieldValues.FileRef -TargetUrl "$($targetFolder.ServerRelativeUrl)/$($file.FieldValues.FileLeafRef)" -Force } catch { Write-Error "移动文件 [$($file.FieldValues.FileLeafRef)] 失败: $_" } } # 断开连接 Disconnect-PnPOnline
关键说明
- 参数替换:务必将脚本中的
$siteUrl、$libraryName替换为你的实际站点和库信息 - 日期格式适配:如果你的“Document date”是固定格式(如
dd/MM/yyyy),请将日期解析部分替换为:if (-not [DateTime]::TryParseExact($docDateStr, "dd/MM/yyyy", $null, [System.Globalization.DateTimeStyles]::None, [ref]$docDate)) { # 警告逻辑 } - 批量处理优化:脚本通过
-PageSize 500实现分页,避免大数量文件请求超时 - 测试建议:先选取少量文件测试脚本逻辑,确认无误后再执行全量移动
内容的提问来源于stack exchange,提问作者gokulnath
相关产品推荐
相关产品推荐

