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...
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.
carlintveld
Aug 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>