PowerCLI script to copy PortGroup between hosts

Here is a short PowerCLI script to copy vSwitch PortGroups from a source host to a target host. Security policies will be copied too. The switch at the target host has to be created already. The script takes inheritance into account. This means just setting, changed at PortGroup-level are copied. All other settings are inherited.

Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope Session -Confirm:$false
Connect-VIServer "host01", "host02" -User root -Password Password

$SourceHost = Get-VMHost host01
$TargetHost = Get-VMHost host02
$CopySwitch = "vSwitch0"
$VMKernelPortGroup = ($SourceHost | Get-VMHostNetworkAdapter -VMKernel).PortGroupName

$SourceHost | Get-VirtualSwitch -Name $CopySwitch | Get-VirtualPortGroup -Standard | where {$_.Name -notin $VMKernelPortGroup} | foreach {
    $CopiedPortGroup = $TargetHost | Get-VirtualSwitch -Name $CopySwitch | New-VirtualPortGroup -Name $_.Name -VLanId $_.VLanID
    if (($_.ExtensionData.Spec.Policy.Security).count -gt 0) {
        if ($_.ExtensionData.Spec.Policy.Security.AllowPromiscuous -ne $null) {
            $CopiedPortGroup | Get-SecurityPolicy | Set-SecurityPolicy -AllowPromiscuous $_.ExtensionData.Spec.Policy.Security.AllowPromiscuous
        if ($_.ExtensionData.Spec.Policy.Security.MacChanges -ne $null) {
            $CopiedPortGroup | Get-SecurityPolicy | Set-SecurityPolicy -MacChanges $_.ExtensionData.Spec.Policy.Security.MacChanges
        if ($_.ExtensionData.Spec.Policy.Security.ForgedTransmits -ne $null) {
            $CopiedPortGroup | Get-SecurityPolicy | Set-SecurityPolicy -ForgedTransmits $_.ExtensionData.Spec.Policy.Security.ForgedTransmits


  • First line enables to connect to more than one host at a time, which happens in second line. Of course you can connect to a vCenter.
  • Within the loop I use ExtensionData to get security policy information for the PortGroup. When policy is not set at PortGroup-level, ExtensionData at this point is $null.
  • At line 7 I get a list of all VMKernel ports to not copy them.

One response to “PowerCLI script to copy PortGroup between hosts”

  1. rajashekhar Betha says:

    Hi vNote42,

    Thanks for your script on host to host port group copy.

    it make me easy to append port groups between hosts easy.

    best regards
    Rajashekhar Betha

Leave a Reply

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