Forum Discussion
Christian Forjahn
Mar 25, 2017Brass Contributor
PowerShell: Find VNet of an ARM VM
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...
Jakob Gottlieb Svendsen
Mar 29, 2017Copper Contributor
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. :)
Christian Forjahn
Mar 30, 2017Brass Contributor
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.
- carlintveldAug 15, 2020Brass Contributor
I have revised the script with the following guidance:
- No looping
- No dependencies on additionally required pieces of information, e.g. resource group
$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)])
Or you could just pick the resource group and vnet name with `$subnet.split("/")[4]` and `$subnet.split("/")[8]`.Obviously this solution assumes a particular structure of the subnet resourceid. I wonder if there is a utility function in the Az modules package somewhere that helps with that./subscriptions/<guid>/resourceGroups/<resourcegroupname>/providers/Microsoft.Network/virtualNetworks/<vnetname>/subnets/<subnetname>