You can always force the result into an array, either when assigning the return value of your cmdlet to a variable:
$x = @(Get-myObjects)
$x.Length
or "on-demand":
$x = Get-myObjects
@($x).Length
Question
I am using a Cmdlet which can return one or more elements:
PS C:\Users\admin> $x = Get-myObjects
PS C:\Users\admin> $x
ComputerName : test-2
Description : n/a
Id : cbcb1ece-99f5-4478-9f02-65a622df8a98
IsActive :
MinNum : 0
Name : scom-test2-mp
modeType : 1
PSComputerName :
If I use length attribute I get nothing.
PS C:\Users\admin> $x.length
PS C:\Users\admin>
Yet, if the Get-myObjects
cmdlet returns 2 or more, then it is a collection and I can get .length
attribute.
How can I get the .length to work if the Get-myObjects cmdlet returns a single object for one object value?
Solution
You can always force the result into an array, either when assigning the return value of your cmdlet to a variable:
$x = @(Get-myObjects)
$x.Length
or "on-demand":
$x = Get-myObjects
@($x).Length
OTHER TIPS
Use the Measure-Object
cmdlet. It's a little clunky here because you can't just get the count in an elegant way.
$x = Get-myObjects
$x | measure-object
Output:
Count : 1
Average :
Sum :
Maximum :
Minimum :
Property :
If you just want the count:
$x | measure-object | select -ExpandProperty Count
Output:
1
I noticed that in this case it is better to use the foreach
loop of powershell.
reference of logical loops in PowerShell
example:
foreach($i in $x)
{
Write-Host $i.Name
}
The above example works for both when $x has one element or more.