Mar 25 2017 03:00 AM - last edited on Jul 23 2018 01:20 PM by Eric Starker
Mar 25 2017 03:00 AM - last edited on Jul 23 2018 01:20 PM by Eric Starker
Hi everyone,
it took me quite some time to find a way to get the VNet an ARM VM belongs to by using PowerShell. I don't think this is the perfect solution, but I would like to share it in order someone else needs to find out. I would be interested in better ways of getting attached networks. I will start the discussion with this code snippet
$vnets= Get-AzureRmVirtualNetwork
$vm = Get-AzureRmVM -name $newVm.Name -ResourceGroupName $newRG
$vmIPId = $vm.NetworkProfile.NetworkInterfaces.Id
foreach ($vnet in $vnets){
$vnetIPId = $vnet.Subnets.IpConfigurations.Id
if ($vnetIPId.Startswith($vmIPId) ){
$vnetName = $vnet.Name
return
}
}
Cheers Christian
Mar 26 2017 09:02 AM
Mar 29 2017 01:33 PM - edited Mar 29 2017 01:34 PM
Mar 29 2017 01:33 PM - edited Mar 29 2017 01:34 PM
Hello!
Funny, that it isnt straight forward to get the vNet!
I tried to do it using another method, but in the end I am not sure it is better than yours. :)
$RG = "HybridWorkers" $VMName = "AA10" Login-AzureRmAccount $VM = Get-AzureRMVM -ResourceGroupName $RG -Name $VMName $VMNicName = $vm.NetworkProfile.NetworkInterfaces.Id.Split("/")[-1] $VMNic = Get-AzureRmNetworkInterface -ResourceGroupName $RG -Name $VMvNetName = $VMNic.IpConfigurations.Subnet.Id.Split("/")[8] $vNet = Get-AzureRmVirtualNetwork -ResourceGroupName $RG -Name $VMvNetName $vNet
It think it is quite weird that the command outputs this "Id" but afaik the other commands cannot use that as input to get a resource. :)
Mar 30 2017 12:25 AM
Nice. This was one of my approaches as well.
What I wanted to automate was to get the vNet without knowing the ResourceGroup it belongs to.
Oct 18 2017 02:54 AM
Not really innovating, just bringing it down to a single line:
$vnetName = Get-AzureRmVirtualNetwork | % {if($_.Subnets.IpConfigurations.Id.StartsWith($vm.NetworkProfile.NetworkInterfaces.Id)){return $_.Name}}
Aug 15 2020 03:06 AM
I have revised the script with the following guidance:
$vm = get-azvm -name azpbagentdvm01
$nic = get-aznetworkinterface -resourceid $vm.NetworkProfile[0].NetworkInterfaces[0].Id
$subnetresourceid = $nic.IpConfigurations[0].Subnet.id
$split = $subnetresourceid.split("/")
$vnetresourceid = [string]::Join("/", $split[0..($split.Count - 3)])
Nov 24 2021 06:41 PM
This seems simpler to me because I don't know how to program like you guys do. Maybe it will help a sysadmin like myself.
$SourceVmObject = Get-AzVM -name 'HPG-DA-2'
$SourceVMNIC = $SourceVmObject.NetworkProfile.NetworkInterfaces[0].Id | Get-AzNetworkInterface
$SourceSubscriptionVnets = Get-AzVirtualNetwork
$SourceSubscriptionVnet = $SourceSubscriptionVnets | where {$_.subnets.ipconfigurations.id -eq $SourceVMNIC.IpConfigurations.id}
$SourceSubscriptionVnet.Name