$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?
First, use the array sub-expression operator @( ... ). This operator returns the result of one or more statements as an array. If there is only one item, the array has only one member. Use Write-Output with the switch -NoEnumerate to prevent PowerShell from un-rolling the array.
You can use the += operator to add an element to an array. The following example shows how to add an element to the $a array. When you use the += operator, PowerShell actually creates a new array with the values of the original array and the added value.
Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.
What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.
Try $x = @(get-aduser)
The @() syntax forces the result to be an array
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With