Script to fetch VM list from all resource groups across particular subscription

Varma 1,380 Reputation points
2024-02-27T03:39:28.44+00:00

is there any PowerShell script which will list all the resource groups having virtual machines from particular subscription. I would like to export to CSV file and use it. basically I am looking for all virtual machines list from particular subscription across Pr subscription. and I dont want to miss any resource group and virtual machine. Thank you

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
7,817 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zahra Ahmadi Firouz Jaee 615 Reputation points
    2024-02-27T03:55:20.9133333+00:00

    May this thread helps you: https://learn.microsoft.com/en-us/answers/questions/992897/powershell-script-to-get-list-of-all-vms-in-all-su Or this script as summary:

    # Define the output CSV file path
    $file = "C:\path\to\your\output.csv"
    
    # Get all Azure subscriptions
    $Subscriptions = Get-AzSubscription
    
    # Initialize an array to store VM information
    $VMs = @()
    
    # Loop through each subscription
    foreach ($Subscription in $Subscriptions) {
        # Set the current subscription context
        Set-AzContext -SubscriptionId $Subscription.Id
    
        # Get all VMs in the subscription
        $VMs += Get-AzVM
    }
    
    # Create a custom object for each VM
    $VMReport = $VMs | ForEach-Object {
        [PSCustomObject]@{
            Subscription = $_.Context.Subscription.Name
            ResourceGroup = $_.ResourceGroupName
            VMName = $_.Name
        }
    }
    
    # Export the VM information to CSV
    $VMReport | Export-Csv -Path $file -NoTypeInformation
    
    # Display a message
    Write-Host "VM information exported to $file"
    
    
    

    ** Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful **


1 additional answer

Sort by: Most helpful
  1. Prrudram-MSFT 24,371 Reputation points
    2024-03-01T05:39:33.5233333+00:00

    Hi @Varma

    Please check if this helps, this SO answer has the script that you are looking for. I might need to make some changes accordingly
    https://stackoverflow.com/questions/77654246/powershell-script-that-gets-executed-on-list-of-vms-of-an-azure-subscription

    --please don't forget to "[Accept the answer]" if the reply is helpful--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.