Share via

Script to get resource information

Narayanan, Krishnaprasad 21 Reputation points
2021-11-11T14:51:29.453+00:00

Hi,

Is there any script or option to get the following information related to VM's in a single go.

Information I required are,

Subscription
VM name
RG
Tags (mine has 10 tags)
Disks attached
Tags assigned the Disks
Nic
Tags assigned the Nic

Azure Virtual Machines
Azure Virtual Machines

An Azure service that is used to provision Windows and Linux virtual machines.

Azure Virtual Network
Azure Virtual Network

An Azure networking service that is used to provision private networks and optionally to connect to on-premises datacenters.


1 answer

Sort by: Most helpful
  1. Purna Rao 26 Reputation points
    2021-11-11T17:44:42.327+00:00
    [string]$subscriptionName='<Subscription_Name>'
    Connect-AzAccount
    
    Set-AzContext -Subscription $subscriptionName 
    
    $RGs=Get-AzResourceGroup 
    
    $VMInfo=@()
    
    foreach($rg in $RGs)
    {
        $VMs=Get-AzVM -ResourceGroupName $rg.ResourceGroupName
        $disks=Get-AzDisk -ResourceGroupName $rg.ResourceGroupName
    
        foreach($vm in $VMs)
        {
            $vmObject=New-Object -TypeName Object    
            $vmObject | Add-Member -NotePropertyName VMName -NotePropertyValue $vm.Name
            $vmObject | Add-Member -NotePropertyName RG -NotePropertyValue $vm.ResourceGroupName
            $vmObject | Add-Member -NotePropertyName Subscription -NotePropertyValue $subscriptionName
            $VMdisks=@()
            foreach($disk in $disks)
            {
                if($disks.ManagedBy -like "*$($vm.Name)*")
                {
                    $VMdisks+=$disk.Name
                }
            }
            $VMNics=$vm.NetworkProfile.NetworkInterfaces.id -join ','
            $NICTags=@()
            foreach($vNIC in $VMNics)
            {
                $resource=Get-AzResource -ResourceId $vNIC
                $NICTags+=$resource.Tags
            }
            $VMNICTags=$NICTags -join ','
            $vmObject | Add-Member -NotePropertyName NIC -NotePropertyValue $VMNics
            $vmObject | Add-Member -NotePropertyName NICTags -NotePropertyValue $VMNICTags
            $vmDisks=$VMdisks -join ','
            $vmObject | Add-Member -NotePropertyName DisksAttached -NotePropertyValue $vmDisks
            $VMInfo+=$vmObject
        }
    }
    $VMInfo | Export-CSV -path c:\windows\temp\VMInfo.csv
    

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

Your answer

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