In case you didn’t see my last article about automating the creation of Port Groups in an enterprise VMware environment, I highly recommend you do, since this second script is all about copying the existing Port Groups from one host to a new one. This is useful when we are adding a new host to the cluster and we need to configure all of the VLANs on it. Let’s go!

Add-PSSnapin VMware.VimAutomation.Core
$portgroups = Get-VirtualSwitch -VMHost esxi-1.lab.local -Name vSwitch0 | Get-VirtualPortGroup | where {$_.Name -like "VMXNET*"}
ForEach ($pg in $portgroups) 
{
   $pgname =$pg.Name
   $pgvlan = $pg.VlanId
   Get-VirtualSwitch -VMhost esxi-2.lab.local -Name vSwitch0 | New-VirtualPortGroup -name $pgname -VLanId $pgvlan
}

VMware PowerCLI – Copy Port Groups Script image 1

Table of Contents

    Of course, before we jump into running the script let’s have a look and see exactly what it’s up to.

    Add-PSSnapin VMware.VimAutomation.Core – here we are adding the PowerCLI snapin to the PowerShell session to be able to take advantage of all the VMware CLI Commands.

    $portgroups = Get-VirtualSwitch -VMHost, etc. – In this nice line, we specify the host we want to copy the VLANs from. We save all the VLANs into one array called $PortGroups.

    ForEach ($pg in $portgroups)
    {
       $pgname =$pg.Name
       $pgvlan = $pg.VlanId
       Get-VirtualSwitch -VMhost esxi-2.lab.local -Name vSwitch0 | New-VirtualPortGroup -name $pgname -VLanId $pgvlan
    }

    In our last script block, we access each element of the array, retrieve the Port Group Name and VLAN ID and then we run the New-VirtualPortGroup against the new host that we just added to the cluster using the VLAN ID and PG Name variables we created from the array.

    Please comment or leave any suggestions.

    Have a nice SysAdmin day!

    Leave a Reply

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