Add new virtualportgroup to vSwitch on multiple VMHosts with Powercli

If you dont have dvSwitches (Distributed vSwitches) in your vSphere cluster, or dont even have a cluster, you may have to add new portgroups manually, depending on the number of VMHosts this can be a pretty cumbersome task.

Luckily, we can use powercli to automate the task. In the following example i will use the -location parameter to define my tagets in the variable $hosts

Lets go ahead and define the VMhosts we want to target:

$hosts=get-vmhost -location “location”

Then, we create the new portgroup for every VMhost in the location by using a foreach loop:

foreach ($vmhost in $hosts) {Get-VMHost $vmhost | Get-VirtualSwitch -name “vSwitch0” | New-VirtualPortGroup -VLanId “10” -Name “Name”}

This will create a new VirtualPortGroup with VLAN ID 10 named “Name” on vSwitch0 on all the VMHosts in the specified location.

Remove the port again by doing this:

foreach ($vmhost in $hosts) {Get-VMHost $vmhost | Get-VirtualSwitch -name “vSwitch0” | Get-VirtualPortGroup -Name “Name” | Remove-VirtualPortGroup -Confirm:$false}

Remember that -Confirm:$false will remove the port without confirmation! Make sure you have the right targets in the $hosts variable!!!