This PowerShell query breaks, if the item name contains query operators such as "and" or "child". How should I escape it, so that they don't break it?

$SourceItemPath = $SourceItem.Paths.path
$SourceAncestorItem = Get-Item -Path "master:" -Query "$SourceItemPath/ancestor-or-self::*[@@templatekey='my template key']"
  • 1
    Have you tried wrapping the name in # #. This would likely be an issue with the Sitecore API rather than SPE, consider verifying with documentation supporting the query format. – Michael West Feb 13 at 11:24
  • 1
    Yes, I used Dmytro's answer, which worked fine. Thanks. – James Walford Feb 13 at 12:15
up vote 6 down vote accepted

In Sitecore Query, you escape keywords and whitespaces by surrounding path parts with hashes.

To make your query work, prepare the path like this:

$SourceItemPath = $SourceItemPath -replace '[^/]*(and|or|child|descendant|\s)[^/]*','#$&#'

This will convert /some/path/bla and bla/something to /some/path/#bla and bla#/something

  • 1
    Thanks, that works a treat, though I'm not a fan of regular expressions (find them too opaque). I was hoping I'd just missed a syntax trick. – James Walford Feb 13 at 12:14
  • 2
    Added a link to this question in the SPE Gitbook. – Michael West Feb 13 at 17:08

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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