powershell - 使用 Microsoft Graph API 将文件上传到 SharePoint Online
问题描述
我真的是 Microsoft Graph API 的新手,我使用 powershell 创建了一个脚本来从 Microsoft 365 获取报告,并且它被保存在我的驱动器上 ( c:\temp\reports.xlsx
)。
保存后,我希望将其上传到 SharePoint Online。在阅读文档时,微软表示要执行以下请求,
PUT /sites/{site-id}/drive/items/{parent-id}:/{filename}:/content
然后我尝试将它应用到我的用例中,这是我的要求:
function RestMethod {
Param (
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$Request,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$RequestMethod,
[parameter(Mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String]$Body
)
$Headers = @{
Authorization = "$($global:RequestToken.token_type) $($global:RequestToken.access_token)"
}
$RestResults = $null
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
try {
$RestResults = Invoke-RestMethod -Uri $Request -Headers $Headers -Method $RequestMethod -ContentType "application/json"
} catch {
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}
return $RestResults
}
$upLoadRequest = "https://graph.microsoft.com/v1.0/sites/tenant.sharepoint.com/drive/items/Test:/$($File):/content"
$upLoadResults = RestMethod $upLoadRequest 'PUT'
该$File
变量包含c:\temp\reports.xlsx
获取报告时保存我的 excel 文件的目录。我的Test
Url 中是我在Documents
我的站点上创建的文件夹。但是在执行请求时,我得到了这个:
StatusCode: 400
StatusDescription: Bad Request
请帮忙
谢谢
解决方案
变更清单:
- 在提供的问题文件中的地址不正确,因为它需要在库
Test
文件夹下上传Documents
,可以这样解决:有关更多详细信息,
/v1.0/sites/{tenant}.sharepoint.com/drive/root:/Test/reports.xslt:/content
请参阅在 OneDrive 上的驱动器中寻址资源 Upload
端点 的文件内容丢失,可以通过-InFile
参数提供,例如Invoke-RestMethod -InFile $path ...
这是一个最小的例子:
$access_token = "--access token goes here--"
$path = "--path to local file, e.g. c:\data\report.xlsx--"
$url = "https://graph.microsoft.com/v1.0/sites/{tenant}.sharepoint.com/drive/root:/{folder}/{filename}:/content"
$headers = @{'Authorization' = "Bearer $access_token" }
Invoke-RestMethod -Uri $url -Headers $headers -Method Put -InFile $path -ContentType 'multipart/form-data'
推荐阅读
- python-3.x - python:kivy动画计数执行
- mysql - 如何将父表中的数据更新或插入到子表中?
- c++ - 如何将二维数组中的元素索引存储到一维数组中,然后交换这些值
- javascript - 使用js控制台比较网页的两个数字
- android - snapshot.hasData 总是返回 false
- ansible - 如何在ansible中使用expect
- nosql - Couchbase 默认管理员密码更改
- html - 如何在网站上使用Icomoon图标,更改图标颜色以及将来添加更多图标?
- c# - 在 C# 中按 dateTime 对统一文件夹中的模型重新排序
- angular - 我有大约 30 个社交链接字段来获取每个我想使用 formArray 构建的 url