powershell 如何通过Power Shell脚本和Rest API将文件上载到Azure DevOps

cmssoen2  于 2022-12-13  发布在  Shell
关注(0)|答案(1)|浏览(140)

我需要使用rest API和power shell脚本将文件上载到Azure DevOps存储库。我执行了以下操作:

$token = "token"
$authHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($token)")) }

$folderPath = "C:/"
$fileName = "TestTXT.txt"
$body = [System.IO.File]::ReadAllBytes("$folderPath/$fileName")

$org = "orgName"
$project = "projectName"

$createAttachmetUrlTemplate = "https://dev.azure.com/$org/$project/_apis/wit/attachments?fileName={fileName}&api-version=5.0"
$postUrl = $createAttachmetUrlTemplate -replace "{filename}", $fileName

$result = Invoke-RestMethod -Uri $postUrl -Method Post -ContentType "application/json" -Headers $authHeader -Body $body

我已经得到了相应的id和url结果https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest-6.1&tabs=HTTP#upload-a-binary-file

但是我的存储库中没有任何新文件。它在哪里?出了什么问题?我如何在我的存储库中存储文件?

fcg9iug3

fcg9iug31#

你上传文件的REST API Attachments - Create - REST API运行良好,它上传文件到附件存储而不是你的repo,url显示文件的存储地址,你可以通过url下载文件。
如果要在存储库中存储文件,可以使用以下REST API:Pushes - Create
例如:上传一个upload.txt到我的存储库
网址

POST https://dev.azure.com/fabrikam/_apis/git/repositories/{repositoryId}/pushes?api-version=4.1

请求正文

{
  "refUpdates": [
    {
      "name": "refs/heads/main",
      "oldObjectId": "the objectId of ref"
    }
  ],
  "commits": [
    {
      "comment": "Added upload.txt file.",
      "changes": [
        {
          "changeType": "add",
          "item": {
            "path": "/upload.txt"
          },
          "newContent": {
            "content": "this is conetent of upload.txt",
            "contentType": "rawtext"
          }
        }
      ]
    }
  ]
}

测试 Postman :

您将在存储库中看到upload.txt

相关问题