49
$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?

2

4 Answers 4

57

Try $x = @(get-aduser)

The @() syntax forces the result to be an array

4
  • 1
    This won't result in an array containing an array if the result is an array? What if the function results $null? (PowerShell is so confusing because of all the magic they do sometimes.)
    – jpmc26
    Mar 11, 2015 at 17:01
  • This is one of those annoying things about Powershell. With this solution you'll have an array with one element which is an array, so your Count property will be 1 even though the array inside could have many elements, which means you can't use it directly in a for loop. Feb 8, 2017 at 6:15
  • @DavidKlempfner, in most cases you will not have array with single element.
    – filimonic
    Aug 7, 2020 at 9:48
  • Years later and I came across this problem again. This time a for loop was not entering because the array was turned into an object because it was one element. I had to check the Count property for null before entering the for loop. Jan 25, 2021 at 6:21
18

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.

4

Also, you can use $x=[array]get-aduser

0

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]
2
  • This is effectively the same answer as the currently accepted one, but with less information. Is there more you can add to your answer to flesh it out?
    – Ross
    Mar 29, 2018 at 18:06
  • I will add comment. Some collections are internally 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.
    – filimonic
    Aug 7, 2020 at 9:46

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.