VMware

PowerCLI is official! What’s new? | Main | Don’t forget – PowerCLI Webinar next Wednesday at 9:00 a.m. PDT

May 27, 2009

Moving custom fields from one vCenter to another.

If you’re looking at upgrading to vSphere, one thing that may come in handy is an easy and flexible way to move custom fields from your old vCenter to your new one. With PowerCLI this is quite easy… except for one thing: there is no Get-CustomField cmdlet! The why is a long story but it turns out it’s pretty easy to write just such a thing. In fact here it is:

function Get-CustomField {
 param($item)
 
 foreach ($cf in $item.CustomFields) {
  if ($cf.Value) {
   $field = "" | Select Key, Value, EntityName
   $field.Key  = $cf.Key
   $field.Value  = $cf.Value
   $field.EntityName = $item.Name
   Write-Output $field
  }
 }
}

Not too hard at all, really. So how do we use this? One nice feature of PowerCLI that often gets overlooked is its ability to connect to multiple vCenters at once and manage them all. We can take advantage of this to connect to both our old vCenter and our new one, and move the values directly between them. The way this works is to store the output of Connect-VIServer in a variable, then pass this variable to later cmdlets to specify the server you want to manage. For example:

$server1 = Connect-VIServer vcserver1
$server2 = Connect-VIServer vcserver2

This next bit of code will take all custom fields on all VMs in vcserver1 and transfer them to vcserver2. This assumes the VMs already exist in both locations.

$fields = Get-VM -server $server1 | Foreach { Get-CustomField $_ }
$vms = Get-VM -server $server2
foreach ($field in $fields) {
 $vm = $vms | Where { $_.Name -eq $field.EntityName }
 Set-CustomField -Entity $vm -Name $field.Key -Value $field.Value
}

That’s really all there is to it. If you need to transfer custom fields on more than just VMs, say maybe you also have fields on ESX hosts, you can use a more general bit of code that will do this for all types of objects. I’ve added that example to my script repository and you can download it here.

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d8341c328153ef01156fb4a0d9970c

Listed below are links to weblogs that reference Moving custom fields from one vCenter to another.:

Comments

Post a comment

If you have a TypeKey or TypePad account, please Sign In.