PowerShell:如何强制将结果作为Array而不是Object获取

时间:2022-07-29 21:14:55
$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个或更多结果,我得到$ x作为数组,但如果我只有一个结果,则得到$ x作为对象。如何使它更正确,总是收到数组 - 空,一个元素或一些元素?

3 个解决方案

#1


28  

Try $x = @(get-aduser)

试试$ x = @(get-aduser)

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

@()语法强制结果为数组

#2


3  

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

此外,您可以使用$ x = [array] get-aduser

#3


-1  

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]

#1


28  

Try $x = @(get-aduser)

试试$ x = @(get-aduser)

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

@()语法强制结果为数组

#2


3  

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

此外,您可以使用$ x = [array] get-aduser

#3


-1  

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]