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

使用PowerShell和Invoke-RestMethod获取Azure DevOps仓库文件遇异常

问题分析与解决方法

问题根源

你直接使用了浏览器中查看仓库文件的网页URL,这个地址是面向前端页面的,并非Azure DevOps的REST API端点,因此调用时会返回“Page not found”错误。要获取仓库文件内容,必须使用Azure DevOps官方提供的Git REST API接口。

修正步骤

  1. 构造正确的API请求地址
    Azure DevOps获取仓库文件的API格式为:

    https://dev.azure.com/{组织名}/{项目名}/_apis/git/repositories/{仓库名}/items?path={文件路径}&api-version={API版本}
    

    其中:

    • {组织名}:你的Azure DevOps组织名称
    • {项目名}:所属项目名称
    • {仓库名}:目标仓库的名称(示例中为PostmanCollections)
    • {文件路径}:文件在仓库中的完整路径,需以/开头(示例中为/PostmanFunctionalTest/PostmanFunctionalTest.postman_collection.json)
    • {API版本}:推荐使用稳定的预览版,比如7.1-preview.1
  2. 修正后的PowerShell代码

    $personalToken = "***"
    $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalToken)"))
    $header = @{authorization="Basic $token"}
    
    # 替换为你的实际参数
    $organization = "你的组织名"
    $project = "你的项目名"
    $repoName = "PostmanCollections"
    $filePath = "/PostmanFunctionalTest/PostmanFunctionalTest.postman_collection.json"
    $apiVersion = "7.1-preview.1"
    
    $apiUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repoName/items?path=$filePath&api-version=$apiVersion"
    $response = Invoke-RestMethod -Uri $apiUrl -Method GET -Headers $header
    
    # 解码API返回的base64格式文件内容
    $decodedContent = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($response.content))
    $decodedContent
    
  3. 关键说明

    • API返回的文件内容默认以base64编码存储在content字段中,必须解码才能得到实际的JSON文本
    • 确保个人访问令牌(PAT)拥有仓库读取权限,否则会返回权限错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:26:08