方法调用失败,因为 [Sitecore.Data.Items.Item] 不包含名为 'op_Addition' 的方法

Method invocation failed because [Sitecore.Data.Items.Item] does not contain a method named 'op_Addition'

我有一个 powershell 脚本,我需要在其中创建符合条件的项目的报告,但我需要将这些项目存储在列表 (guiltyItems) 中,在我的函数上下文之外,以及来自返回标题。

Method invocation failed because [Sitecore.Data.Items.Item] does not contain a method named 'op_Addition'

这里失败了:$global:guiltyItems += $_;

Sitecore powershell 中是否有创建 Sitecore 项目列表并填充它的方法?

如果有任何相关性,对 Process-Richtext 函数的调用是从一个 foreach 循环进行的,该循环在另一个 foreach 循环中:

$global:guiltyItems = $null;

function Process-RichText
{
    param(  [Parameter(Mandatory = $true)] [Sitecore.Data.Fields.Field]$field,
            [Parameter(Mandatory = $true)] [string]$pattern,
            [Parameter(Mandatory = $true)] [Sitecore.Data.Items.Item]$_)

    $allMatches = [System.Text.RegularExpressions.Regex]::Matches($field.Value,$pattern);
    foreach ($match in $allMatches)
    {
        $currentItem = Get-Item master -Id ([Sitecore.Data.ID]::Parse($match.Groups["sitecoreid"].Value)).Guid;

        if ($currentItem.Template.Id -eq $quiltyTemplate)
        {
            $global:guiltyItems += $_;
        }
    }
}

[...]

ForEach ($item in $allItems) {
    foreach ($field in $item.Fields)
    {
        if ($field.Id -eq $RichTextContentID -and ($field.Value -match $internalLinkPattern))
        {
           Process-RichText $field $internalLinkPattern $item;
        }
    }
}

谢谢

问题是由动态类型引起的。该脚本首先将 guiltyItems 设置为 null,因此它没有类型。到目前为止没有什么奇怪的。 foreach 循环中出现输入问题。

$global:guiltyItems = $null;
...
foreach ($match in $allMatches) {
    ...
    if ($currentItem.Template.Id -eq $quiltyTemplate) {
        $global:guiltyItems += $_; # Boom!

所以这里发生的是 null 变量没有类型。在 foreach 循环中,处理过的变量确实有类型,因为它们不是空值。第一次迭代会将 guiltyItems 设置为迭代对象的任何类型。与错误消息声明一样,添加两个 Sitecore.Data.Items.Item 没有任何意义。

guiltyItems声明为数组时,加法有意义。它不是将两个 Sitecore 项目添加在一起,而是将新元素添加到集合中。

如果您的集合只包含一个元素,脚本可能会正常运行。那是因为加法只调用了一次。

根据评论,要解决此问题,请像这样将 $global:guiltyItems 明确声明为数组,

$global:guiltyItems = @()