使用 powershell 获取 Azure DevOps 服务连接服务主体 id

Get Azure DevOps service connection service principal id with powershell

我正在致力于自动化 Azure Active Directory 应用程序注册和 Azure Devops 服务连接,但遇到了困难。

我想通过服务主体 ID(或至少获取 ID)查询 Azure DevOps 服务连接(服务端点)。这在使用 Azure CLI 时是可能的:

az devops service-endpoint list --query "[?authorization.parameters.serviceprincipalid=='xxx']"

但是由于我在 Azure 自动化帐户中 运行 这个是 powershell runbook,所以不支持 Azure CLI。

然后我尝试了 Azure DevOps REST API,并从 powershell 调用它,但响应不包含服务主体 ID,而只是这样:

authorization : @{parameters=; scheme=ServicePrincipal}

有人知道如何解决这个问题吗?

更新

我这样称呼其余 API:

$uriAccount = $UriOrg + "_apis/serviceendpoint/endpoints?endpointNames={name}&api-version=6.1-preview.4"
$result = Invoke-RestMethod -Uri $uriAccount -Method get -Headers $AzureDevOpsAuthenicationHeader 

$result.value 给了我这个:

authorization : @{parameters=; scheme=ServicePrincipal}

您可以试试 REST API Endpoints - Get Service Endpoints By Names.

GET https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4

在此 REST API 中,您可以通过服务连接的名称找到 ID 和详细信息。

这是在 PowerShell 中使用 REST API 的示例:

$token = "{pat}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4"
$head = @{ Authorization =" Basic $token" }
Invoke-RestMethod -Uri $url -Method GET -Headers $head

更新:

出现这个问题的原因是你result的输出方式不对

对于 JSON 响应主体,如果不指定最后一层,则没有直观的方法来获取结果。 这是我修改后的代码,请注意我如何打印 result:

$token = "{pat}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/{organization}/{project}/_apis/serviceendpoint/endpoints?endpointNames={endpointNames}&api-version=6.0-preview.4"
$head = @{ Authorization =" Basic $token" }
$reslut = Invoke-RestMethod -Uri $url -Method GET -Headers $head
echo $result.value.authorization.parameters