由于这个问题不断出现,让我补充一些 Mathias R. Jessen's effective solution背景信息:
因此,只需将 , 放在数组变量之间即可不是工作,因为它创造了一个锯齿状(嵌套)数组:
# Two arrays with property names.
$user_props = @('propA', 'propB')
$user_groups = @('grpA', 'grpB')
# !! WRONG: This passes a *jagged* array, not a flat one.
# -> ERROR: "Cannot convert System.Object[] to one of the following types
# {System.String, System.Management.Automation.ScriptBlock}."
'foo' | Select-Object $user_props, $user_groups
# !! WRONG:
# The same applies if you tried to combine one or more *literal* property names
# with an array variable.
'foo' | Select-Object 'propA', $user_groups
'foo' | Select-Object $user_groups, 'propA', 'propB'
也就是说,$user_props, $user_groups 有效通过
@( @('propA', 'propB'), @('grpA', 'grpB') ),即一个锯齿状(嵌套)数组,
而你需要通过的是
@('propA', 'propB', 'grpA', 'grpB'),即一个平坦的大批。
Mathias 的解决方案很方便,因为您不必知道或关心 $user_props 和 $user_groups 是否包含数组或者只是一个属性名称,由于如何@(...),array-subexpression operator有效 - 结果将是一个平面数组:
# Note how the variable references are *separate statements*, whose
# output @(...) collects in an array:
'foo' | Select-Object @($user_props; $user_groups)
# Ditto, with a literal property name.
# Note the need to *quote* the literal name in this case.
'foo' | Select-Object @('propA'; $user_groups)
在实践中,它不会对这个用例产生影响,所以这是一个方便实用的解决方案,但通常值得注意的是@(...)枚举数组变量用作其中的语句,然后将结果收集到一个新的大批。也就是说,$user_props 和 $user_groups 都被发送到管道逐个元素,并且结果,组合的元素被收集在一个新的数组中。
平面连接数组的直接方法(或将单个元素附加到数组)是使用+ 具有(至少)一个数组值的运算符LHS.这必然会返回一个新的作为 LHS 数组的副本的数组,其中直接附加了 RHS 的元素:
# Because $user_props is an *array*, "+" returns an array with the RHS
# element(s) appended to the LHS element.
'foo' | Select-Object ($user_props + $user_groups)
如果您不确定 $user_props 是否为大批,您可以简单地转换为 [array],它也适用于单个文字属性名称:
# The [array] cast ensures that $user_props is treated as an array, even if it isn't one.
# Note:
# 'foo' | Select-Object (@($user_props) + $user_groups)
# would work too, but would again needlessly enumerate the array first.
'foo' | Select-Object ([array] $user_props + $user_groups)
# Ditto, with a single, literal property name
'foo' | Select-Object ([array] 'propA' + $user_groups)
# With *multiple* literal property names (assuming they come first), the
# cast is optional:
'foo' | Select-Object ('propA', 'propB' + $user_groups)
笔记: