Search code examples
powershellsharepointsharepoint-2010powershell-3.0

Escape single quotes in PowerShell


I'm trying to build a SharePoint 2010 listdata.svc query that resembles:

http://server/FooList/_vti_bin/listdata.svc/FooList?$select=Title,Id,OwnerId,Status&$filter=(OwnerId eq 1234 and Status eq 'Ready')

Single quotes don't work:

$url = $url + '&$filter=(OwnerId eq 1234 and Status eq 'Ready')'

Nor does escaping them with back-ticks:

$url = $url + '&$filter=(OwnerId eq 1234 and Status eq `'Ready`')'

If I use double quotes, $filter is replaced with a zero-length string (it's not a variable in the script):

$url = $url + "&$filter=(OwnerId eq 1234 and Status eq 'Ready')"

What's the correct way to escape single quotes?


Solution

  • You need to double the quotes when using single-quoted string literals:

    '&$filter=(OwnerId eq 1234 and Status eq ''Ready'')'
                                             ^^     ^^
    

    Demo:

    PS > '&$filter=(OwnerId eq 1234 and Status eq ''Ready'')'
    &$filter=(OwnerId eq 1234 and Status eq 'Ready')
    PS >
    

    Using backticks only works with double-quoted string literals (since they process escape sequences), but then you also need to escape all other special characters (e.g. the $ in variable names):

    PS > "&`$filter=(OwnerId eq 1234 and Status eq `"Ready`")"
    &$filter=(OwnerId eq 1234 and Status eq "Ready")
    PS >
    

    But in a single-quoted string literal, the ` is treated as a literal backtick.