You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本实现SharePoint文件夹及子文件夹文件下载

递归下载SharePoint Online文件夹及子文件夹文件的PowerShell脚本

原脚本仅能获取指定目录下的直接文件,无法遍历子文件夹并下载其中内容。要实现递归下载,我们可以通过递归函数来处理文件夹的层级结构,具体修改如下:

# Site collection URL
$SiteURL = "https://mysite.sharepoint.com/sites/WinTest"

# Connect to SharePoint Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin

$LibraryRelativeURL = "/Shared Documents/TEST" # Relative Path of the Library
$DownloadPath = "C:\Users\User1\Downloads\TestFolder"         # Local directory to save downloaded files

# 创建递归函数处理文件夹及子文件夹
function Download-SPFolder {
    param(
        [string]$SPFolderRelativeUrl,
        [string]$LocalFolderPath
    )

    # 如果本地文件夹不存在则创建
    if (-not (Test-Path -Path $LocalFolderPath)) {
        New-Item -ItemType Directory -Path $LocalFolderPath | Out-Null
        Write-Host "创建本地文件夹: $LocalFolderPath"
    }

    # 获取当前文件夹下的所有文件和子文件夹
    $folderItems = Get-PnPFolderItem -FolderSiteRelativeUrl $SPFolderRelativeUrl -ItemType All

    # 处理文件:下载到对应本地路径
    foreach ($item in $folderItems | Where-Object { $_.FileSystemObjectType -eq "File" }) {
        $localFilePath = Join-Path -Path $LocalFolderPath -ChildPath $item.Name
        Write-Host "正在下载文件: $($item.Name)"
        Get-PnPFile -Url $item.ServerRelativeUrl -Path $LocalFolderPath -FileName $item.Name -AsFile -Force | Out-Null
    }

    # 处理子文件夹:递归调用函数
    foreach ($item in $folderItems | Where-Object { $_.FileSystemObjectType -eq "Folder" }) {
        $childSPFolderUrl = "$SPFolderRelativeUrl/$($item.Name)"
        $childLocalFolderPath = Join-Path -Path $LocalFolderPath -ChildPath $item.Name
        Download-SPFolder -SPFolderRelativeUrl $childSPFolderUrl -LocalFolderPath $childLocalFolderPath
    }
}

# 启动递归下载
Download-SPFolder -SPFolderRelativeUrl $LibraryRelativeURL -LocalFolderPath $DownloadPath

Write-Host "所有文件下载完成!"

关键修改说明

  • 新增Download-SPFolder递归函数,接收SharePoint文件夹相对路径和本地保存路径作为参数
  • 每次进入函数先检查并创建对应的本地文件夹,保证本地目录结构与SharePoint一致
  • 同时获取当前文件夹下的所有类型项(文件+文件夹),分别处理:
    • 文件:直接调用Get-PnPFile下载到本地对应路径
    • 子文件夹:拼接新的SharePoint路径和本地路径,递归调用函数继续处理下一层级

内容的提问来源于stack exchange,提问作者altermix101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 08:12:44