Ok, so I just wasted 30 minutes debugging the logic of my script, I have run in to this before but had forgotten about it.
Beware of arrays as object properties…
So at first glance you’d think that this code would be just fine, I mean, what is wrong with initializing a variable property as an array and then pushing object to it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Initialize properties var spec = new VcVirtualMachineConfigSpec(); spec.vAppConfig = new VcVmConfigSpec(); spec.vAppConfig.property = new Array(); // Create new property spec var newProperty = new VcVAppPropertySpec(); // Set values newProperty.operation = VcArrayUpdateOperation.edit; newProperty.info.key = property.key; // Add property spec to array spec.vAppConfig.property.push(newProperty); // Reconfigure the VM VirtualMachine.reconfigVM_Task(spec); |
However, this will not work. You can’t push objects in to the array property once you assign it to the object. So you have to change your code to something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Initialize properties var spec = new VcVirtualMachineConfigSpec(); spec.vAppConfig = new VcVmConfigSpec(); // spec.vAppConfig.property = new Array(); // Create new property spec var newProperty = new VcVAppPropertySpec(); // Set values newProperty.operation = VcArrayUpdateOperation.edit; newProperty.info.key = property.key; // Add property spec to array var propertyspecs = new Array(); propertyspecs.push(newProperty); // Assign array spec.vAppConfig.property = propertyspecs; // Reconfigure the VM VirtualMachine.reconfigVM_Task(spec); |
As you can see, instead of initializing spec.vAppConfig.property as an array and pushing objects to that array, instead I had to create a new array object, push objects to it and then assign it to spec.vAppConfig.property. Not a big deal but it can make the logic of the code messier.