VMware Cloud Community
mpverr
Enthusiast
Enthusiast

Strange inconsistency when using setCustomValue

I have a custom field called: "Date Handed To Customer". The scope of this in VC is per VM.

When I run the following script it works great - EXCEPT I have one or two virtual machines where it does not work.

$CustomVarName = "Date Handed To Customer"

$varVMName = "<virtual Machine Name>"

$varfileMachineDate = "10/10/2008"

$vm = Get-View -ViewType virtualmachine -Filter @{"Name"=$varVMName}

$vm.setCustomValue($CustomVarName, $varFileMachineDate)

When I run it with the first virtual machine, it works great. When I change it to the second one, it fails on the last line where the setCustomValue is performed. The Get-View works which has me total confused.

The error I get is:

Method invocation failed because [http://System.Object[|http://System.Object[]] doesn't contain a method named 'setCustomValue'.

At line:1 char:19

+ $vm.setCustomValue( <<<< $CustomVarName, $varFileMachineDate)

What's even more confusing is when I go $vm | gm I actually see the method.

Any help would be appreciated.

thanks

0 Kudos
5 Replies
LucD
Leadership
Leadership

It looks as if your 2nc call to Get-View is returning an array of VirtualMachine objects instead of one VirtualMachine object.

You could check by doing after the 2nd Get-View

$vm.gettype()

For an array you should see a BaseType of "System.Array".


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

0 Kudos
mpverr
Enthusiast
Enthusiast

That is what has me perplexed as I had checked that as well and it returns what it should.

C:\Program Files\VMware\Infrastructure\VIToolkitForWindows> $vm.gettype()

IsPublic IsSerial Name BaseType

-


-


-


-


True True Object[] System.Array

0 Kudos
LucD
Leadership
Leadership

That confirms that the 2nd call returns an array.

And you can't use a VirtualMachine method (SetCustomValue in this case) on an array of VirtualMachine objects.

As a solution for both cases you can use a foreach loop.

The foreach loop will handle if it is a single object or an array of objects

$vm = get-view -ViewType VirtualMachine -filter @{"Name"=$varVMName}
$vm | %{$_.SetCustomValue($CustomVarName, $varFileMachineDate)}


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

0 Kudos
mpverr
Enthusiast
Enthusiast

But what has me confused is just this one VM has the issue.

0 Kudos
LucD
Leadership
Leadership

Can you do the following frmo the prompt

Get-View -ViewType VirtualMachine -Filter @{"Name"=$varVMName | select Name

and see how many guests are returned ?

It must be more than one.


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

0 Kudos