如何用PowerShell向SPO添加含弯引号的列表项
问题描述
- 需求:通过PowerShell调用Graph API批量端点(
https://graph.microsoft.com/v1.0/$batch)向SharePoint Online列表导入包含弯引号的数据,已知站点和列表ID。 - 现象:在Graph Explorer中提交POST请求可成功插入数据,弯引号显示正常;但执行PowerShell脚本时,返回「Invalid Payload」错误。
- 已尝试:采纳建议后未达预期,已附上VS Code中PowerShell终端及版本信息截图。
Graph Explorer 成功请求示例
{ "requests": [ { "id": "755154", "method": "POST", "url": "/sites/{site-id}/lists/{list-id}/items/", "body": { "fields": { "Title": "Something “and” something" } }, "headers": { "Content-Type": "application/json" } } ] }
报错的PowerShell脚本
$tenant_id = "some-tenant-id-here" $client_id = "a-valid-client-id" # from App registration $client_secret = "the-client-secret" # from App registration $authParams = @{ TenantId = $tenant_id ClientId = $client_id ClientSecret = $client_secret | ConvertTo-SecureString -AsPlainText -Force } $auth = Get-MsalToken @authParams $batch = @' { "requests": [ { "id": "755154", "method": "POST", "url": "/sites/{site-id}/lists/{list-id}/items/", "body": { "fields": { "Title": "Something “else” here" } }, "headers": { "Content-Type": "application/json" } } ] } '@ $headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $($auth.AccessToken)" } $uri = "https://graph.microsoft.com/v1.0/`$batch" $result = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -Body $batch $result
解决方案
问题根源是硬编码JSON字符串时,PowerShell的默认编码可能导致Graph API无法正确解析Unicode弯引号。改用PowerShell对象构建请求体再转换为JSON,可确保编码符合标准。
修改后的脚本:
$tenant_id = "some-tenant-id-here" $client_id = "a-valid-client-id" # 来自应用注册 $client_secret = "the-client-secret" # 来自应用注册 $authParams = @{ TenantId = $tenant_id ClientId = $client_id ClientSecret = $client_secret | ConvertTo-SecureString -AsPlainText -Force } $auth = Get-MsalToken @authParams # 用PowerShell对象构建批量请求,避免硬编码JSON的编码问题 $batchRequest = @{ requests = @( @{ id = "755154" method = "POST" url = "/sites/{site-id}/lists/{list-id}/items/" body = @{ fields = @{ Title = "Something “else” here" } } headers = @{ "Content-Type" = "application/json" } } ) } # 将对象转换为JSON,确保Unicode字符正确编码,-Depth指定足够深度避免截断 $batchJson = $batchRequest | ConvertTo-Json -Depth 3 $headers = @{ "Content-Type" = "application/json; charset=utf-8" "Authorization" = "Bearer $($auth.AccessToken)" } $uri = "https://graph.microsoft.com/v1.0/`$batch" $result = Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -Body $batchJson $result
关键说明
- 用对象构建请求体:避免直接写JSON字符串,PowerShell对象转JSON时会自动处理Unicode字符(如弯引号),生成符合Graph API要求的标准JSON。
- 指定JSON深度:
ConvertTo-Json默认深度为2,这里用-Depth 3确保嵌套的请求体结构不被截断。 - 明确编码类型:在请求头中指定
charset=utf-8,进一步确保请求编码正确。
内容的提问来源于stack exchange,提问作者EduardoCMB
相关产品推荐
相关产品推荐

