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
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
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
But what has me confused is just this one VM has the issue.
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