$result = Get-ADUser -Filter $filter
If I have 2 or more results, I get $x as array, but if I have only one result, a get $x as object. How to make it more correct, to always recieve array - empty, with one element or with some elements?
$result = Get-ADUser -Filter $filter
If I have 2 or more results, I get $x as array, but if I have only one result, a get $x as object. How to make it more correct, to always recieve array - empty, with one element or with some elements?
Try $x = @(get-aduser)
The @()
syntax forces the result to be an array
$null
? (PowerShell is so confusing because of all the magic they do sometimes.)
By the way, the other solutions in this question are not really the best way to do this, for the reasons stated in their comments. A better way is simply to put a comma before the function, like
$result = ,(Get-ADUser -Filter $filter)
That will put an empty result into an empty array, a 1 element result into a 1 element array and a 2+ element result into an array of equal elements.
I had the same issue using an indexed value in a loop. I fixed it by changing
$PatchGroupData.SCCM_Collection[$i]
to
@($PatchGroupData.SCCM_Collection)[$i]
IEnumerable
type. IEnumerable does not have index ([n]
) accessor, so they should be converted to array to have index. Theoretically, IEnumerable sequence CAN be infinite, so conversion to finite array not possible, but this is very rare case.
Aug 7, 2020 at 9:46