Hello and welcome to all VMware admins. For the few of us who have an enterprise scale VMware environment with hundreds of VLANs and servers, setting up a new VLAN on all our ESXi hosts can be a daunting task.

That’s why I came up with this script that will make our life easier and will add the new VLAN/Network/PortGroup to all ESXi hosts that are part of a specific cluster.

Table of Contents
     Add-PSSnapin VMware.VimAutomation.Core
     #Variables
     $viserver = "vcenter.lab.local"
     $cluster = "Production"
     $vSwitch = "vSwitch0"
     $PGName = "VMXNET-VLAN-200"
     $PGVLANID = "200"
    
     Connect-VIserver $viserver -User "user" -Password "password"
     $vmhosts = Get-Cluster $cluster | Get-VMhost
    
     ForEach ($vmhost in $vmhosts)
     {
     Get-VirtualSwitch -VMhost $vmhost -Name $vSwitch | New-VirtualPortGroup -Name $PGName -VlanId $PGVLANID
     }
    

    VMware PowerCLI – Create Port Groups Script image 1

    Before we run this script and enjoy work being done for us for a change, let’s dissect it and see what every line does.

    Add-PSSnapin VMware.VimAutomation.Core – adds the PowerCLI SnapIn to the PowerShell session so we can take advantage of all the CLI commands.

    $viserver = “vcenter.local” – specifies the vCenter server we want to connect to
    $cluster = “Production” – specifies the cluster that all the ESXi hosts are a part of
    $vSwitch = “vSwitch0” – specifies the vSwitch we want to add the new VLANs (Networks/PortGroups) to
    $PGName = “VMXNET-VLAN-200” – here we specify the name of the new VLAN/Network/PortGroup
    $PGVLANID = “200” – and here is where we put in the VLAN ID (most important component)

    Now that all our variables are in place, let’s start creating the new Port Groups.

    Connect-VIserver $viserver -User “lab.local\admin” -Password “1234567” – On this line we connect to the vCenter server and we supply the username and password so that we won’t get any prompts.

    $vmhosts = Get-Cluster $cluster | Get-VMhost – Here we are getting all the cluster resources and, more specifically, retrieving all the ESXis and outputting them as an array to a variable called $vmhosts.

    Now that we have all our info retrieved, it’s time to actually create the Port Groups:

    ForEach ($vmhost in $vmhosts)
     {
          Get-VirtualSwitch -VMhost $vmhost -Name $vSwitch | New-VirtualPortGroup -Name $PGName -VlanId $PGVLANID
     }

    Here we go into a ForEach loop. For each element in the $vmhosts array, we run the New-VirtualPortGroup command with the variables we declared in the first section.

    That’s it! Simple isn’t it? Thanks for taking the time to read this tutorial, and hope it helps everybody out there have a more productive day!