使用PowerShell和Invoke-RestMethod获取Azure DevOps仓库文件遇异常
问题分析与解决方法
问题根源
你直接使用了浏览器中查看仓库文件的网页URL,这个地址是面向前端页面的,并非Azure DevOps的REST API端点,因此调用时会返回“Page not found”错误。要获取仓库文件内容,必须使用Azure DevOps官方提供的Git REST API接口。
修正步骤
构造正确的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
修正后的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关键说明
- API返回的文件内容默认以base64编码存储在
content字段中,必须解码才能得到实际的JSON文本 - 确保个人访问令牌(PAT)拥有仓库读取权限,否则会返回权限错误
- API返回的文件内容默认以base64编码存储在
内容的提问来源于stack exchange,提问作者user19560879
相关产品推荐
相关产品推荐

