I'm writing a script to show the missing/new items between two content branches. For the target of the comparison, I build an item path and then call Get-Item on that path to see if there is an equivalent item. The problem is that Get-Item throws an exception if no item is found - I would just like to handle a case of a 'null' item in my script.

#$source is the root path of the source branch
$localPath = $sourceItem.Paths.FullPath.SubString($source.Length)
$targetPath = "master:" + $target + "/" + $localPath
$targetItem = Get-Item $targetPath

The script works in that $targetItem is null if no item is found using $targetPath but I would like to suppress the error message in the script.

  • 1
    Have you considered using Compare-Object? This may be more efficient for you. Essentially use Get-ChildItem for both trees and compare two properties (item path such as /sitecore/content/home). Apr 24, 2017 at 21:45

1 Answer 1


Just use the standard PowerShell error handling parameters:

$localPath = $sourceItem.Paths.FullPath.SubString($source.Length)
$targetPath = "master:" + $target + "/" + $localPath
$targetItem = Get-Item $targetPath -ErrorAction Ignore

Sounds like in your case this would be more than enough. But if you want the ability to check for other potential errors, you could combine the SilentlyContinue action with the ErrorVariable option, and then act out based on what's in the variable. For instance:

# ...
$targetItem = Get-Item $targetPath -ErrorAction SilentlyContinue -ErrorVariable myError
if ($myError.Count -gt 0 -and
    !($myError[0].FullyQualifiedErrorId.Contains("ItemDoesNotExist"))) {
    Write-Warning $myError[0]

Lots more details in this blog post: https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/09/handling-errors-the-powershell-way/

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.