locked
How to retrieve all the virtual machines in Azure with the cost using PowerShell command RRS feed

  • Question

  • I am trying to get all the available virtual machines in Azure with their VM series name, specs and the cost associated with each. The result should needs with VMs with Linux and VMs with Windows separately to to pull. 

    I have used the following PowerShell command, but it does only retrieves VM name with the specs - 

    Get-AzureRmVmSize -location "southeastasia"


    Dileepa S. Rajapaksa
    ---------------------------------
    Cloud Soulution Architect
    ----------------
    Twitter : @dsrajapaksa
    Blog : http://windowsgeek.lk/

    Thursday, February 27, 2020 2:54 AM

All replies

  • Thanks for reaching out! Here is a solution that you can try to achieve your requirement. Below scripts retrieves the list of VM's in a subscription.

    #Provide the subscription Id where the VMs reside
    $subscriptionId = ""
    
    Login-AzAccount
    Select-AzSubscription $subscriptionId
    
    $report = @()
    $vms = Get-AzVM
    $publicIps = Get-AzPublicIpAddress 
    $nics = Get-AzNetworkInterface | ?{ $_.VirtualMachine -NE $null} 
    foreach ($nic in $nics) { 
        $info = "" | Select VmName, ResourceGroupName, Region, VirturalNetwork, Subnet, PrivateIpAddress, OsType, PublicIPAddress 
        $vm = $vms | ? -Property Id -eq $nic.VirtualMachine.id 
        foreach($publicIp in $publicIps) { 
            if($nic.IpConfigurations.id -eq $publicIp.ipconfiguration.Id) {
                $info.PublicIPAddress = $publicIp.ipaddress
                } 
            } 
            $info.OsType = $vm.StorageProfile.OsDisk.OsType 
            $info.VMName = $vm.Name 
            $info.ResourceGroupName = $vm.ResourceGroupName 
            $info.Region = $vm.Location 
            $info.VirturalNetwork = $nic.IpConfigurations.subnet.Id.Split("/")[-3] 
            $info.Subnet = $nic.IpConfigurations.subnet.Id.Split("/")[-1] 
            $info.PrivateIpAddress = $nic.IpConfigurations.PrivateIpAddress 
            $report+=$info 
        } 
    $report | ft VmName, ResourceGroupName, Region, VirturalNetwork, Subnet, PrivateIpAddress, OsType, PublicIPAddress 
    

    You can use for loop to send each VM name to Get-AzConsumptionUsageDetail to get details of consumption of each VM.

    Hope this helps!
    Monday, March 2, 2020 10:35 AM