如何使用 PowerShell 从资源组中获取 azure 资源?

要使用 PowerShell 从资源组中获取可用资源,我们需要使用Get-AZResource命令。假设我们有资源组名称AnsibleTestRG并且我们需要从资源组中检索资源,那么我们将使用以下命令。

示范

Get-AzResource -ResourceGroupName AnsibleTestRG

要过滤输出,

输出结果

Get-AzResource -ResourceGroupName AnsibleTestRG | Select Name, ResourceType, Location
输出结果

如果特定订阅中有多个资源组,我们可以使用以下命令将资源从资源组导出到 CSV 文件。

示范

$ErrorActionPreference = "Stop"
try {
    Connect-AZAccount
    Set-AzContext -SubscriptionName 'Your Subscription Name'
    $rgs = Get-AzResourceGroup

    foreach ($rg in $rgs.ResourceGroupName) {
        Write-Output "Checking Resource Group: $rg"
        Get-AzResource -ResourceGroupName $rg | Select Name, ResourceGroupName, Type, Location | Export-Csv .\AzureResources.csv -Append -Force -NoTypeInformation
    }
}
catch {
    Write-Host "$($_.Exception.Message)" -BackgroundColor DarkRed
}