如何将源位置最新创建的文件复制到SharePoint空间及PowerShell实现
你现有逻辑是将本地路径的近期文件复制到本地目标路径,要同步到SharePoint可以选择以下两种方案:
方案1:映射SharePoint为本地网络驱动器(修改成本最低)
前置操作:先将目标SharePoint文档库映射为本地网络盘符(例如Z盘),无需修改原有代码的核心逻辑
# 筛选近5天创建的文件,若仅需最新1个文件可调整下方筛选逻辑 $filterDate = (Get-Date).AddDays(-5).Date $sourcePath = "C:\repo\scripts\Copy move files\source\*.*" # 替换为你映射的SharePoint驱动器对应的目标路径 $spTargetPath = "Z:\报告存放目录\" $Files = Get-ChildItem -Path $sourcePath -File -ErrorAction SilentlyContinue | Where-Object {$_.TimeCreated -ge $filterDate} # 仅需要最新1个文件时,在上面的管道后追加以下代码: # | Sort-Object TimeCreated -Descending | Select-Object -First 1 foreach($File in $Files){ Copy-Item -Path $File.FullName -Destination $spTargetPath -Force }
方案2:PnP PowerShell直连上传(更稳定,无需映射驱动器)
无需配置网络映射,直接调用SharePoint官方接口上传,适合服务器定时任务场景:
- 提前安装依赖模块:运行
Install-Module -Name PnP.PowerShell -Scope CurrentUser完成安装 - 首次运行会弹出身份验证窗口,无人值守场景可替换为证书认证实现静默登录
# 配置参数 $siteUrl = "https://你的组织域名.sharepoint.com/sites/你的站点名称" $sourcePath = "C:\repo\scripts\Copy move files\source\*.*" $spLibraryName = "共享文档" # 替换为你的目标SharePoint文档库名称 $spTargetFolder = "/共享文档/报告存放路径" # 替换为SharePoint内目标文件夹的相对路径 $filterDate = (Get-Date).AddDays(-5).Date # 连接SharePoint站点 Connect-PnPOnline -Url $siteUrl -Interactive # 筛选要上传的文件 $Files = Get-ChildItem -Path $sourcePath -File -ErrorAction SilentlyContinue | Where-Object {$_.TimeCreated -ge $filterDate} # 仅需要最新1个文件时,在上面的管道后追加以下代码: # | Sort-Object TimeCreated -Descending | Select-Object -First 1 # 批量上传到SharePoint foreach($File in $Files){ Add-PnPFile -Path $File.FullName -Folder $spTargetFolder -ErrorAction Stop } # 断开连接 Disconnect-PnPOnline
注意事项:
- 文件名如果含
#、%等SharePoint禁止的特殊字符,建议提前做清洗避免上传报错- 如果需要实现移动而非复制操作,上传完成后可追加
Remove-Item $File.FullName删除本地源文件
内容的提问来源于stack exchange,提问作者apl
相关产品推荐
相关产品推荐

