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 '18 at 11:24
  • 1
    Yes, I used Dmytro's answer, which worked fine. Thanks. – James Walford Feb 13 '18 at 12:15

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

| improve this answer | |
  • 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 '18 at 12:14
  • 2
    Added a link to this question in the SPE Gitbook. – Michael West Feb 13 '18 at 17:08

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.