tl;dr:
-
$ListItemCollection
属于类型[System.Management.Automation.PSObject]
,不是数组。
-
Make sure that it is an array (e.g., $ListItemCollection = @()
) for +=
to work as intended, i.e., for +=
to append an element[1].
-
请注意,命令通常 output multiple物品 - 然后定期收集[object[]]
数组,如果分配给变量 - 仅输出scalar如果命令碰巧只返回one物品;换句话说:单项输出数组会自动展开的.
-
因此,如果命令有可能仅返回single对象,还你需要结果always be an array, use @(...)
, the 数组子表达式运算符; e.g.:
# @(...) ensures that $file is an array, even if just 1 file matches
$files = @(Get-ChildItem *.txt)
该错误消息意味着$ListItemCollection
属于类型[System.Management.Automation.PSObject]
and not数组。
由于类型[pscustomobject]
([System.Management.Automation.PSObject]
) 没有静态op_Addition
方法,您不能使用+
运算符及其实例作为 LHS。
(特定于类型的运算符被实现为静态op_*
方法)。
您可以按如下方式验证这一点:
PS> (New-Object System.Management.Automation.PSObject) + 1 # !! Breaks
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'
如果要检查给定类型的运算符支持,请使用如下命令,使用[datetime]
键入作为示例:
PS> [datetime] | Get-Member -Force -Static -Type Method op_*
TypeName: System.DateTime
Name MemberType Definition
---- ---------- ----------
op_Addition Method static datetime op_Addition(datetime d, timespan t)
op_Equality Method static bool op_Equality(datetime d1, datetime d2)
op_GreaterThan Method static bool op_GreaterThan(datetime t1, datetime t2)
op_GreaterThanOrEqual Method static bool op_GreaterThanOrEqual(datetime t1, datetime t2)
op_Inequality Method static bool op_Inequality(datetime d1, datetime d2)
op_LessThan Method static bool op_LessThan(datetime t1, datetime t2)
op_LessThanOrEqual Method static bool op_LessThanOrEqual(datetime t1, datetime t2)
op_Subtraction Method static datetime op_Subtraction(datetime d, timespan t), static timespan op_Subtraction(datetime d1, datetime d2)
Note:
-
“原始”.NET 数据类型not有这样的方法,因为操作员对它们的支持是内置的。
-
同样,PowerShell本身也实现了+
对于数组和集合([object[]]
, [System.Collections.Generic.List[object]]
,...),但请注意:
- 总是构造一个新实例,并且
- 结果是always类型的
[object[]]
(除非您使用类型约束变量将数组转换回不同的集合类型)。
-
-Force
是需要的,因为Get-Member
隐藏op_*
默认方法。
[1] Technically, a new array is created behind the scenes, because arrays are immutable. In loops this can be a performance concern; if so, use a mutable collection type such as [System.Collections.Generic.List[object]]
and append to it with its .Add()
method.