Solving problems invented by others...
Get all vlans used in a vSphere environment

Get all vlans used in a vSphere environment

Some days ago a colleague asked me how he can list all vlan ids used in our vSphere environment. Simple question, but the answer wasn´t that easy.

While analyzing what i get when using the Get-VDPortgroup commandlet i see 2 different types of return values. The first ones are normal portgroups with vlan ids. The second ones are vlan trunks which we used to connect virtual firewalls. Sadly these two types use a different data structure. While a normal portgroup reveals its vlan id with the VlanConfiguration.VlanId property, a vlan trunk uses VlanConfiguration.Ranges which is a array of ranges consisting of of a StartVlanId and a EndVlanId.

So first i had to treat this two types of portgroups differently. Then i had to find a way to generate from a range, consisting of a start and a end value, a list of vlan ids.

Long story short, i came to the following solution:

1.) Create an empty array.


This array will be filled with all vlan ids i will extract from the portgroups.

2.) Use a one liner which looks terrifying to make it look complicated.

(Just joking. I inserted line breaks and insertions to make it readable.)

Get-VDPortgroup | 
Where-Object -FilterScript { $_.IsUplink -eq $false } |
   if ($_.VlanConfiguration.VlanType -like "*Vlan*")
      foreach ($range in $_.VlanConfiguration.Ranges)
         for ($i=$range.StartVlanId; $i -le $range.EndVlanId;$i++)


First i fetch all portgroups. Then i filter them to exclude the uplink portgroups of the distributed switch. (Uplink portgroups are trunks with a vlan range from 0-4096, which would be not very useful to include in our vlan list.)
Next i check if the portgroup is a normal portgroup (VlanType -like "*Vlan*"). The vlan id there could be easily added to the predefined array.
If the portgroup is a vlan trunk, then i had to loop through all ranges which could be found in the property VlanConfiguration.Ranges. With every range i step from the StartVlanId to EndVlanId and add every step to the predefined array.

3.) Remove duplicates

Since the same vlan id could be used in more than one portgroup or trunk i got a list with duplicate entries. The following command deals with that and remove the duplicates.

$vlans | Sort-Object -Unique



So, with this 3 commands you´ll get a list of vlan ids used in your environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

ninety two − eighty three =