如何修改PowerShell代码将大文件上传至SharePoint库子文件夹
我刚好碰到过一模一样的场景!原代码默认是把文件传到文档库的根目录,要改成传子文件夹,核心就是找到目标子文件夹的对象,而不是直接用文档库的RootFolder。下面是具体的修改思路和完整代码示例:
核心修改思路
- 先明确你的目标子文件夹路径(比如文档库叫
Documents,子文件夹是Project/AnnualReports,这是相对于库根目录的路径) - 替换原代码中获取根文件夹的逻辑,改成逐步定位到目标子文件夹(还能自动创建不存在的子文件夹)
- 把文件上传的目标路径指向这个子文件夹,而不是库根目录
修改后的完整代码
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" # 配置你的SharePoint信息 $SiteURL = "https://yourtenant.sharepoint.com/sites/yoursite" $LibraryName = "Documents" $SubFolderPath = "Project/AnnualReports" # 子文件夹路径,相对于库根目录 $LocalFilePath = "C:\YourLargeFiles\BigDataFile.csv" # 获取用户凭据 $Cred = Get-Credential $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName, $Cred.Password) # 初始化CSOM上下文 $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Context.Credentials = $Credentials try { # 获取目标文档库 $Library = $Context.Web.Lists.GetByTitle($LibraryName) $Context.Load($Library) $Context.ExecuteQuery() # 定位/创建目标子文件夹(支持多层嵌套) $CurrentFolder = $Library.RootFolder foreach ($FolderSegment in $SubFolderPath.Split("/")) { try { # 尝试获取现有文件夹 $CurrentFolder = $CurrentFolder.Folders.GetByUrl($FolderSegment) $Context.Load($CurrentFolder) $Context.ExecuteQuery() } catch { # 如果文件夹不存在,自动创建 $FolderCreateInfo = New-Object Microsoft.SharePoint.Client.FolderCreationInformation $FolderCreateInfo.Url = $FolderSegment $CurrentFolder = $CurrentFolder.Folders.Add($FolderCreateInfo) $Context.ExecuteQuery() } } # 分块上传大文件到目标子文件夹 $FileStream = New-Object IO.FileStream($LocalFilePath,[System.IO.FileMode]::Open) $FileCreateInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation $FileCreateInfo.Overwrite = $true $FileCreateInfo.ContentStream = $FileStream # 这里用子文件夹的路径拼接文件名,而不是库根目录 $FileCreateInfo.URL = $CurrentFolder.ServerRelativeUrl + "/" + [System.IO.Path]::GetFileName($LocalFilePath) $UploadedFile = $CurrentFolder.Files.Add($FileCreateInfo) $Context.Load($UploadedFile) $Context.ExecuteQuery() Write-Host "文件上传成功!路径:$($UploadedFile.ServerRelativeUrl)" -ForegroundColor Green } catch { Write-Host "上传出错:$_" -ForegroundColor Red } finally { # 清理资源 if ($FileStream) { $FileStream.Close() } $Context.Dispose() }
关键修改点说明
- 子文件夹定位逻辑:通过循环拆分路径的每一段,逐步找到目标文件夹,还能自动创建不存在的层级,适配多层嵌套的子文件夹场景
- 上传路径替换:把原代码中依赖
Library.RootFolder的部分,全部换成我们定位到的CurrentFolder,确保文件传到正确的子目录 - 容错处理:加入了文件夹存在性判断,避免因为文件夹不存在导致上传失败
如果你确定子文件夹已经存在,可以去掉代码中创建文件夹的try/catch块,直接获取现有文件夹即可。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

