我希望能够从交互式 PowerShell session 调用 Azure REST API 方法。有关如何通过服务主体 here 执行此操作的说明但我希望能够使用我自己的凭据调用这些方法,而不是切换到不同的集合。这将使我更轻松地找出需要在本地调用的方法,并临时从 Azure 收集信息。
我想要使用现有 PowerShell cmdlet 无法完成的调用的示例是
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/products/{productId}/policies/policy? api-version=2019-01-01
最佳答案
当您使用 Login-AzureRmAccount 或 Login-AzAccount 登录 Azure,然后调用 AzureRm 或 Az cmdlet 时,将从 Azure 获取不记名 token 并将其存储在您的上下文对象中。您可以使用 Get-AzureRmContext 或 Get-AzContext 检索上下文对象并解析该对象中的 token 。
$Context = Get-AzContext
$Cache = $Context.TokenCache
$CacheItems = $Cache.ReadItems()
$Token = ($CacheItems | Where-Object { $_.Resource -eq "https://management.core.windows.net/" })
token 将持续一个小时,如果过期,您需要通过再次调用 Azure cmdlet 来更新它(尽管可以通过编程方式更新它)。
这段代码可以封装在一个类似的函数中
function Invoke-AzureRestApi {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$Uri
)
$Context = Get-AzContext
$Cache = $Context.TokenCache
$CacheItems = $Cache.ReadItems()
$Token = ($CacheItems | Where-Object { $_.Resource -eq "https://management.core.windows.net/" })
$Headers = @{Authorization = "Bearer $($Token.AccessToken)"}
Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
}
# run an Az or AzureRm cmdlet to get a token prior to calling the function
Invoke-AzureRestApi -Uri https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/products/{productId}/policies/policy?api-version=2019-01-01
# A simpler example to test the function (though this particular example can be more easily achieved with Get-AzResourceGroup)
Invoke-AzureRestApi -Uri https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups?api-version=2019-08-01
更新(2021 年 8 月 31 日): 现在只需使用 Get-AzAccessToken cmdlet 即可检索 token
function Invoke-AzureRestApi {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$Uri
)
$Token = Get-AzAccessToken
$Headers = @{Authorization = "Bearer $($Token.Token)"}
Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
}
关于azure - 如何从交互式 PowerShell session 调用 Azure REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59163269/