简述:
$ListItemCollection
is of type [System.Management.Automation.PSObject]
, not an array.
Make sure that it is an array (e.g., $ListItemCollection = @()
) for +=
to work as intended, i.e., for +=
to append an element[1].
Note that commands that typically output multiple items - which are then collected in a regular [object[]]
array, if assigned to a variable - output only a scalar if the command situationally happens to return only one item; in other words: a single-item output array is automatically unwrapped.
Therefore, if there's a chance that a command situationally returns only a single object, yet you need the result to always be an array, use @(...)
, the array-subexpression operator; e.g.:
# @(...) ensures that $file is an array, even if just 1 file matches
$files = @(Get-ChildItem *.txt)
错误信息表明
$ListItemCollection
是类型为
[System.Management.Automation.PSObject]
而
不是数组。
由于类型[pscustomobject]
([System.Management.Automation.PSObject]
)没有静态的op_Addition
方法,您不能使用+
运算符与其实例作为LHS。
(特定于类型的运算符被实现为静态的op_*
方法)。
您可以按以下方式进行验证:
PS> (New-Object System.Management.Automation.PSObject) + 1
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)
注意:
.NET的“原始”数据类型没有这些方法,因为它们的运算符支持是内置的。
同样,PowerShell本身实现了数组和集合([object[]]、[System.Collections.Generic.List[object]]等)的+运算符,但需要注意以下几点:
1.新实例总是被构造出来;
2.结果总是是类型[object[]](除非您使用类型约束变量将数组转换回不同的集合类型)。
-Force是必需的,因为Get-Member默认隐藏op_*方法。
[1] 技术上讲,在幕后创建一个新数组,因为数组是不可变的。在循环中,这可能会影响性能;如果是这样,请使用可变的集合类型,如[System.Collections.Generic.List[object]],并使用其.Add()方法进行添加。
foreach
并追加项目?为什么不直接使用$splist.Items | Select-Object PageID,"Html Component"
? - Bill_Stewart$ListItemCollection
?它是什么类型的对象? - EBGreen