Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: How can I to force to get a result as an Array instead of Object

Tags:

powershell

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

like image 949
filimonic Avatar asked Dec 29 '12 19:12

filimonic


People also ask

How do you return an array in PowerShell?

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.

How do you assign a value to an array in PowerShell?

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.

How do I convert a string to an array in PowerShell?

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?

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.


2 Answers

Try $x = @(get-aduser)

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

like image 178
Cédric Rup Avatar answered Sep 19 '22 15:09

Cédric Rup


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.

like image 21
massospondylus Avatar answered Sep 19 '22 15:09

massospondylus