GuruAnt
Contributor
Contributor

Clone VirtualPortGroups from one Host to Another

I'm trying to write some code that will recreate all the port groups (including Security settings) from a particular vSwitch on a source host to a particular vSwitch on a target host. Using LucD's post I got a rough idea, and have this so far:-

# Clone Virtual Port Groups from an existing Host

$strSourceHost = "server1"
$strTargetHost = "server2"
$strSwitch = "vSwitch1"

$viewSourceHost = (Get-VMHost $strSourceHost) | Get-View
$viewTargetHost = (Get-VMHost $strTargetHost) | Get-View

$viewSourceNetSys = Get-View -Id $viewSourceHost.ConfigManager.NetworkSystem
$viewTargetNetSys = Get-View -Id $viewTargetHost.ConfigManager.NetworkSystem

$objSourceHost = Get-VMHost $strSourceHost
$objSourceSwitch = Get-VirtualSwitch -VMHost $objSourceHost | Where-Object {$_.Name -like "$strSwitch"}
$objSourceVPGs = Get-VirtualPortGroup -VMhost $objSourceHost | Where-Object {$_.VirtualSwitchName -like "$strSwitch"}

ForEach ($objSourceVPG in $objSourceVPGs){
$vsConfig = $viewSourceHost.Config.Network.PortGroup | Where-Object { $_.Key -like $objSourceVPG.Key }
$vsSpec = $vsConfig.Spec
$viewTargetNetSys.UpdatePortGroup($objVPG,$vsSpec)
}

I'm not sure if this code works, and I don't have a test environment. Is there a way to "disarm" this (like -WhatIf) so I can see what it will do? Does this look right?

Also, if the target server has some existing port groups with the same names, will these be updated? Or should I delete all port groups from the host before creating new ones?

0 Kudos
2 Replies
ctrople
Enthusiast
Enthusiast

I think you want to use AddPortGroup instead of UpdatePortGroup, otherwise it appears to work correctly in my lab providing that the port group doesn't already exist and the specified vswitch does exist.

$viewTargetNetSys.AddPortGroup($vsSpec)

======================================

Monitor. Correlate. Act. | vWire.com

======================================

Chyna Trople, VCP Monitor. Correlate. Act. | vWire.com
0 Kudos
LucD
Leadership
Leadership

That's correct. If the portgroup doesn't exist on your target server you will have to use AddPortGroup.

With the SDK methods, like AddPortGroup, there is no -WhatIf parameter.

Always make sure to test the script first in your test environment !

The script will indeed be better, if you first test if the portgroup already exists on the target server and take appropriate action.

If the portgroup exists, the AddPortGroup call will fail.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos