azure - 如何从交互式 PowerShell session 调用 Azure REST API

标签 azure powershell

我希望能够从交互式 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/

相关文章:

azure - 如何关闭用户的Azure服务通知?

javascript - 解析 DateTime 值会呈现不同时区的不同日期 - JS

用于删除 Blob 存储中所有文件的 Azure CLI 命令不适用于启用防火墙的 AZ 存储

powershell - 忽略 Powershell 字符串中的通配符 []

sql - 从SQL存储过程中提取毫秒数据

azure - 弃用 login.microsoftonline.com 对 B2C 租户的实际影响

azure - 具有对象 ID 的客户端无权执行标记TrafficConsumers/validate 的操作

powershell - 在 Powershell 中,在路径中输入空格时调用表达式不起作用

powershell - 通过 PowerShell 检查页面重定向

Powershell:给定一个字符串,我如何判断我正在处理的路径类型?