hi
I'm trying to get the output of get-datastore into a array (datagrid).
code:
function Get-Datastores
{
$array = New-Object System.Collections.ArrayList
$Script:GetDatastore = Get-Datastore
$array.AddRange($GetDatastore)
$dataGrid1.DataSource = $array
$form1.refresh()
}
error:
Das Argument "0" mit dem Wert "local_datastore01" für "AddRange" kann nicht in den Typ "System.Collections.ICollection" konvertiert werden: "Der Wert "local_datastore01" vom Typ "VMware.VimAutomation.Cl
ient20.DatastoreImpl" kann nicht in den Typ "System.Collections.ICollection" konvertiert werden."
------snip------
+ $array.AddRange <<<< ($GetDatastore)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
comment:
If I replace the query get-datastore with get-vm the script works fine!
what's wrong? any suggestions?
many thanks and kind regards
Hi there,
This particular call of Get-Datastore returns single object, which cannot be converted to ICollection. But you can do something like this:
if ($GetDatastore -is [array]) {
$array.AddRange($GetDatastore)
} else {
$array.Add($GetDatastore)
}
This will handle both situations - when you get single datastore object or array of datastores.
Vitali
PowerCLI Team
Hi there,
This particular call of Get-Datastore returns single object, which cannot be converted to ICollection. But you can do something like this:
if ($GetDatastore -is [array]) {
$array.AddRange($GetDatastore)
} else {
$array.Add($GetDatastore)
}
This will handle both situations - when you get single datastore object or array of datastores.
Vitali
PowerCLI Team
hi
great, now the script works even there is only one Datastore!
many thanks...
kind regards
You can avoid these kind of errors by using an array subexpression @().
Change this line:
$Script:GetDatastore = Get-Datastore
into
$Script:GetDatastore = @(Get-Datastore)
You should always validate your output. In PowerShell there are three kind of possible return values:
- $null
- an object
- an array of objects (or collection)
When using the array subexpression, you make sure that the output it is always an array and it doesn't matter if zero, one ore more objects are returned.
Arnim
Could you explain the @() bit for me, i see it often but cannot get my mind round it.
thanks, doc.
The @( … ) operation is practically the same as saying [array] $( … )
If the statements in @() return a scalar, it will be wrapped in an array but if the result is already an array, then it won't be nested.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
@() is used to declare an array like:
$a = @()
in this example $a is declared as an empty array
$a = @(get-vm)
in this example the output of get-vm is wrapped in an array.
Cheers,
Arnim