Listing all azure vm belonging to particular subnet

和自甴很熟 提交于 2021-02-10 14:22:09

问题


I want to list all azure vms in a particular subnet. I don't know how to write a PowerShell script for this. I am trying the below but it's not giving the desired output. My desired output- All VMs belonging to subnet having ip 10.87.00.01...10.87.99.99 should get listed in my text file subnet_VM.txt

$tgtIP = "10.87.xx.xx"
$vms = Get-AzureVM

foreach($vm in $vms)
{
  $vmIP = (Get-AzureVM -ServiceName $vm.ServiceName  –Name  $vm.Name).IpAddress
  foreach($ip in $vmIP)
  {
    if($ip -like '$tgtIP*')
    {
       $vm.Name > C:\AZURE\subnet_VM.txt
    }
  }
}

It would be very helpful if I get help on this. Thanks in advance.


回答1:


Note that in Azure the subnets have a name. So a more elegant solution would be to use a subnet name than the raw IP range. Since that is something you are ultimately trying to achieve, I am including that solution as well.

$vms = Get-AzureVM

$tgtSubnet = "Subnet-1"
foreach($vm in $vms)
{
    $thisVM = Get-AzureVM -ServiceName $vm.ServiceName –Name $vm.Name
    $thisVMSubnet = Get-AzureSubnet -VM $thisVM
    if ($thisVMSubnet -eq $tgtSubnet)
    {
        $output  =$output + "`r`n" + $thisVM.Name 
    }
}
$output | Out-File C:\Azure\subnet_VM.txt


来源:https://stackoverflow.com/questions/28985282/listing-all-azure-vm-belonging-to-particular-subnet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!