问题
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