如何在 PowerShell 中使用 Azure REST API?
要使用 PowerShell 使用 Azure REST API,我们首先需要使用 **Connect-AzAccount** 连接到 Azure 云帐户。连接到 Azure 帐户后,您可以使用以下授权标头(与 MS 网站上提供的一样),其中包含一个用于对 REST API 进行身份验证的承载令牌。
$azContext = Get-AzContext
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRm
ProfileProvider]::Instance.Profile
$profileClient = New-Object -
TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -
ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)
$authHeader = @{
'Content-Type'='application/json'
'Authorization'='Bearer ' + $token.AccessToken
}获得授权标头后,您可以将其用于身份验证。现在假设我们需要使用 REST API 列出 Azure 订阅中的所有虚拟机。
https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines/list-all/
我们将使用以下 REST API URL 获取所有虚拟机。
https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute /virtualMachines?api-version=2021-03-01
在这里,我们需要提供一个订阅 ID,从中我们需要列出虚拟机。
我们的命令如下所示:
$restUri = https://management.azure.com/subscriptions/xxxxx-xxxxx-x--xxxxx/providers/Microsoft.Compute/virtualMachines?api-version=2021-03-01
$response = Invoke-RestMethod -Uri $restUri -Method Get -Headers $authHeader
输出

您可以进一步扩展属性。
PS C:\> $response.value | Select Name, location
输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP