Enable MAC Learning as Default on vSphere Distributed Switch

This short PowerCLI script will change the vSphere Distributed Switch default port group configuration to enable MAC learning policy. This means every port group on such switch inherits this configuration and will have MAC learning enabled unless specifically disabled.

For more information why would you need that read William’s Lam blog.

$vds = get-vdswitch 'DSwitch1'
$spec = New-Object VMware.Vim.VMwareDVSConfigSpec
$spec.DefaultPortConfig = New-Object VMware.Vim.VMwareDVSPortSetting
$spec.DefaultPortConfig.MacManagementPolicy = New-Object VMware.Vim.DVSMacManagementPolicy
$spec.DefaultPortConfig.MacManagementPolicy.MacLearningPolicy = New-Object VMware.Vim.DVSMacLearningPolicy

$spec.DefaultPortConfig.MacManagementPolicy.MacLearningPolicy.Enabled = $True
$spec.DefaultPortConfig.MacManagementPolicy.MacLearningPolicy.AllowUnicastFlooding = $True
$spec.DefaultPortConfig.MacManagementPolicy.MacLearningPolicy.Limit = 4000
$spec.DefaultPortConfig.MacManagementPolicy.MacLearningPolicy.LimitPolicy = "DROP"
$spec.ConfigVersion = $vds.ExtensionData.Config.ConfigVersion
$vds.ExtensionData.ReconfigureDvs_Task($spec)

 

Update 08/07/2020

In case you are using this approach for nested vSphere lab instead of the old promiscuous mode, make sure the vmk0 vmkernel port has a different MAC address than the MAC address of the vmnic of the nested ESXi host. This is because when the vmk0 is migrated to a different ESXi host uplink the vDS will not learn the MAC address on the new switch port as it conflicts with the assigned MAC on the first uplink port (same MAC cannot be learnt on two ports).

The vmkernel port MAC can be easily changed by editing /etc/vmware/esx.conf file.

Update 10/06/2021

Forged transmits might be needed to be set as well. Therefore this line needs to be added to the script.

$spec.DefaultPortConfig.MacManagementPolicy.ForgedTransmits = $True