10

In Sitecore Powershell extensions I can use

If ( Get-Item ...)

to return true if an item exists or false if it doesn't, but if the item isn't found then it outputs an error message as well.

Is there a way of checking for an item's existence that doesn't output an error message (and is possibly less intensive than using Get-Item - I only need to know if it's there or not, I don't need to instantiate it)?

3 Answers 3

20

Try this

$database = "master"
$homeItem = "$($database):\sitecore\content\home123"
$homeExists = Test-Path -Path $homeItem
12

An alternative would be to run the Get-Item command and provide the necessary ErrorAction parameter to hide the output.

# Variable $item will contain the object if found.
if(($item = Get-Item -Path "master:\content\home1" -ErrorAction SilentlyContinue)) {
    $item
} else {
    Write-Host "Does not exist."
}

Sometimes you may also see the parameter shortened to -ea 0.

0
1

The above answers above work well if we Get-Item using the Path but unfortunately I was only supplied with item IDs and not Path. So if we Get-Item using ID, exception always occurs even after using -ErrorAction SilentlyContinue. For this case, we will have to use the try-catch block as below -

try { 
        $currentItem = Get-Item -Path "master:" -ID $row.ID -Language "*" -ErrorAction SilentlyContinue
    }
    catch { 
        Write-Log "Item with ID $($row.ID)doesnt exist!"
        continue
    }

Sharing this answer in case you are in same situation as me and you are only supplied with Id of item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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