2

I am trying to execute this script but it is throwing an error.

$path = "/sitecore/content/home"
$root = Get-Item $path
$items = Get-ChildItem $path -Recurse
($items += $root) | Where-Object { $_.TemplateName -eq "Product" -or $_.TemplateName -eq "Accessory" } | ForEach-Object {
    Write-Log "Hi"
}

This part is throwing an error: ($items += $root).

Error:

Failed to call the method because [Sitecore.Data.Items.Item] does not contain a method named "op_Addition"

3

Your code works ok when there are multiple items returned from Get-ChildItem command.

If only 1 item is returned, SPE returns single item object instead of an array.

You can work around the issue by wrapping both $root and $items variables with @(...) like:

$path = "/sitecore/content/home"
$root = @(Get-Item $path)
$items = @(Get-ChildItem $path -Recurse)
($items += $root) | ForEach-Object {
    $_.Name
}
6

Marek's answer is correct and addresses the error, but it's worth bearing in mind that in the situation posted, you have a simpler option available to you:

$path = "/sitecore/content/home"
$items = Get-ChildItem $path -Recurse -WithParent

The -WithParent parameter will automatically include the root item for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.