How to copy custom attributes when migrating vmware vcenter to new database

I recently had to move hosts and guests to a new vcenter server as the old server had become corrupt and full of issues.

The current vcenter has a few custom attributes and notes that would not be transferred as part of the move.

So I wanted to use powercli to read the attributes out and put them back.

To export the attributes I used the script below.

You will need to add as many Key Value pairs as you have custom attributes

 1#load Vmware Module
 2Add-PSSnapin VMware.VimAutomation.Core
 3
 4Connect-VIServer -User 'VMUSER' -Password 'USerPasswd221' -Server 'vcenter1'
 5
 6$vmlist = get-vm
 7$Report =@()
 8foreach ($vm in $vmlist) {
 9$row = "" | Select Name, Notes, Key, Value, Key1, Value1, Key2, Value2, Key3, Value3
10$row.name = $vm.Name
11$row.Notes = $vm | select -ExpandProperty Notes
12$customattribs = $vm | select -ExpandProperty CustomFields
13$row.Key = $customattribs\[0\].Key
14$row.Value = $customattribs\[0\].value
15$row.Key1 = $customattribs\[1\].Key
16$row.Value1 = $customattribs\[1\].value
17$row.Key2 = $customattribs\[2\].Key
18$row.Value2 = $customattribs\[2\].value
19$row.Key3 = $customattribs\[3\].Key
20$row.Value3 = $customattribs\[3\].value
21$Report += $row
22}
23
24$report | Export-Csv "c:\\vms-with-notes-and-attributes.csv" -NoTypeInformation

It should produce a csv file that looks something like this

1VMNAME,NOTES,CREATEDATE,CREATOR,DEPLOYDATE,TEAM
2vmguest1,note1,12/29/2011,Bob,12/30/2011,Web
3vmguest2,note2,12/29/2011,John,12/30/2011,Accounts
4vmguest3,note3,12/29/2011,Paul,12/30/2011,Database

Once you have exported the file you need to import it into the new vCenter

again adding Key Value pairs as needed.

 1#load Vmware Module
 2Add-PSSnapin VMware.VimAutomation.Core
 3
 4Connect-VIServer -User 'VMUSER' -Password 'USerPasswd221' -Server 'vcenter2'
 5
 6$NewAttribs = Import-Csv "C:\\vms-with-notes-and-attributes.csv"
 7
 8foreach ($line in $NewAttribs) {
 9set-vm -vm $line.Name -Description $line.Notes -Confirm:$false
10Set-CustomField -Entity (get-vm $line.Name) -Name $line.Key -Value $line.Value -confirm:$false
11Set-CustomField -Entity (get-vm $line.Name) -Name $line.Key1 -Value $line.Value1 -confirm:$false
12Set-CustomField -Entity (get-vm $line.Name) -Name $line.Key2 -Value $line.Value2 -confirm:$false
13Set-CustomField -Entity (get-vm $line.Name) -Name $line.Key3 -Value $line.Value3 -confirm:$false
14
15}

Hope this helps someone.