如何下载文件名不固定的SharePoint每日报告文件
核心思路
先通过Graph API查询目标文档库中符合命名规则的文件,筛选出当日生成的Full-Report-YYYY-MM-DD-*.csv文件(若一天内存在多个,取最新修改的),再将获取到的文件名传入原下载函数执行下载。
修改后的完整代码
function Get-TargetReportFile { param( [string]$token, [string]$siteId, [string]$driveId ) $headers = @{ "Authorization" = "Bearer $token" "Content-Type" = "application/json" } # 生成当日日期字符串,匹配文件名中的YYYY-MM-DD格式 $today = Get-Date -Format "yyyy-MM-dd" # 构造查询:筛选当日生成的Full-Report开头的csv文件,按修改时间倒序取最新一个 $queryUri = "https://graph.microsoft.com/v1.0/sites/$siteId/drives/$driveId/root/children?`$filter=startswith(name,'Full-Report-$today') and endswith(name,'.csv')&`$orderby=lastModifiedDateTime desc&`$top=1" $response = Invoke-RestMethod -Uri $queryUri -Headers $headers -Method Get if ($response.value.Count -gt 0) { return $response.value[0].name } else { Write-Error "当日未找到符合规则的报告文件" return $null } } function DownloadFile($token, $siteId, $driveId, $filePath, $fileName) { $headers=@{} $headers.Add("Content-Type", "text/plain") $headers.Add("Authorization", "Bearer $token") $response = Invoke-WebRequest -Uri "https://graph.microsoft.com/v1.0/sites/$siteId/drives/$driveId/items/root:/$($fileName):/content" -Method GET -OutFile $filePath -Headers $headers } # 自动下载流程 $targetFileName = Get-TargetReportFile -token $token -siteId $siteId -driveId $driveId if ($targetFileName) { DownloadFile -token $token -siteId $siteId -driveId $driveId -filePath "E:\Log-Files\Latest-Report.csv" -fileName $targetFileName }
代码说明
Get-TargetReportFile函数:- 生成当日日期字符串,匹配文件名中的日期段
- 利用Graph API的筛选器精准定位目标文件,按修改时间倒序确保取到最新文件
- 找到文件则返回文件名,未找到则抛出错误提示
- 主流程:先获取动态生成的文件名,再调用原下载函数完成下载
补充注意事项
- 若报告文件存储在文档库的子目录中,需将
root/children修改为对应路径,例如root:/DailyReports/children - 确保你的访问令牌
$token拥有Files.Read权限,否则无法完成文件查询与下载操作
内容的提问来源于stack exchange,提问作者aasenomad
相关产品推荐
相关产品推荐

