Share via


快速入門:使用 Azure PowerShell 執行 Resource Graph 查詢

本快速入門說明如何使用適用於 Azure PowerShell 的 Az.ResourceGraph 模組來執行 Azure Resource Graph 查詢。 本文也會示範如何排序(排序)並限制查詢的結果。 您可以針對租使用者、管理群組或訂用帳戶中的資源執行查詢。 完成時,您可以移除模組。

必要條件

安裝模組

安裝模組 Az.ResourceGraph ,讓您可以使用 Azure PowerShell 來執行 Azure Resource Graph 查詢。 Azure Resource Graph 模組需要 PowerShellGet 2.0.1 版或更高版本。 如果您已安裝最新版的 PowerShell 和 Azure PowerShell,則您已經擁有所需的版本。

  1. 確認您的 PowerShellGet 版本:

    Get-Module -Name PowerShellGet
    

    如果您需要更新,請移至 PowerShellGet

  2. 安裝模組:

    Install-Module -Name Az.ResourceGraph -Repository PSGallery -Scope CurrentUser
    

    命令會在範圍中 CurrentUser 安裝模組。 如果您需要在範圍中 AllUsers 安裝,請從系統管理 PowerShell 工作階段執行安裝。

  3. 確認模組已安裝:

    Get-Command -Module Az.ResourceGraph -CommandType Cmdlet
    

    此命令會顯示 Cmdlet 版本, Search-AzGraph 並將模組載入 PowerShell 工作階段。

連接到 Azure

從 Visual Studio Code 終端機工作階段中連線到 Azure。 如果您有多個訂用帳戶,請執行命令來設定您訂用帳戶的內容。 使用您的 Azure 訂用帳戶識別碼來取代 <subscriptionID>

Connect-AzAccount

# Run these commands if you have multiple subscriptions
Get-AzSubScription
Set-AzContext -Subscription <subscriptionID>

執行查詢

將模組新增至您的環境之後,您可以執行租用戶型查詢。 此範例中的查詢會傳回五個具有 nametype 每個資源的 Azure 資源。 若要依 管理群組 或訂用帳戶查詢,請使用 -ManagementGroup-Subscription 參數。

  1. 使用 Search-AzGraph Cmdlet 執行 Azure Resource Graph 查詢:

    Search-AzGraph -Query 'Resources | project name, type | limit 5'
    

    此查詢範例不會使用像是的 order by排序修飾詞。 如果您多次執行查詢,可能會為每個要求產生一組不同的資源。

  2. 將查詢更新為 order byname 屬性:

    Search-AzGraph -Query 'Resources | project name, type | limit 5 | order by name asc'
    

    就像先前的查詢一樣,如果您多次執行此查詢,可能會為每個要求產生一組不同的資源。 查詢命令的順序很重要。 在此範例中,order by 會出現在 limit 之後。 查詢會將結果限製為五個資源,然後依名稱排序這些結果。

  3. 將查詢更新為 order byname 屬性,然後將 limit 輸出更新為五個結果:

    Search-AzGraph -Query 'Resources | project name, type | order by name asc | limit 5'
    

    如果此查詢執行數次,且您的環境沒有任何變更,則結果會一致且依 name 屬性排序,但仍限製為五個結果。 查詢會依名稱排序結果,然後將輸出限制為五個資源。

如果查詢未從您已有存取權的訂用帳戶傳回結果,請注意 Search-AzGraph Cmdlet 預設為預設內容中的訂用帳戶。 若要查看屬於預設內容一部分的訂用帳戶標識符清單,請執行此(Get-AzContext).Account.ExtendedProperties.Subscriptions動作 如果您想要搜尋您有權存取的所有訂用帳戶,請執行 來設定 PSDefaultParameterValues Cmdlet 的Search-AzGraph$PSDefaultParameterValues=@{"Search-AzGraph:Subscription"= $(Get-AzSubscription).ID}

清除資源

若要從 PowerShell 工作階段中移除 Az.ResourceGraph 模組,請執行下列命令:

Remove-Module -Name Az.ResourceGraph

若要從您的電腦卸載 Az.ResourceGraph 模組,請執行下列命令:

Uninstall-Module -Name Az.ResourceGraph

可能會顯示 Az.ResourceGraph 模組目前正在使用的訊息。 若是如此,您必須關閉 PowerShell 工作階段並啟動新的工作階段。 然後執行 命令,從您的電腦卸載模組。

若要登出您的 Azure PowerShell 工作階段:

Disconnect-AzAccount

下一步

在本快速入門中,您已將 Resource Graph 模組新增至 Azure PowerShell 環境,並執行查詢。 若要深入瞭解,請移至查詢語言詳細數據頁面。