Search code examples
powershellescapinginvokebackticks

How to get around using apostrophe in double quotes with Powershell


I am working with Powershell. My issue is that my file path (which does not exist on a local computer) has an apostrophe in it. Powershell is seeing this as a single quote, so it is giving me the following error: The string is missing the terminator: '. I thought that I could escape the single quote using a backtick, but that gave me the same error.

The error does not occur when I am doing the first line of code, and I don't even need the backtick for that part. I can even see that the contents of the variable matches up with the file path that I am using. It is only when I am doing the invoke-expression part that it is giving me the error.

I am using https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7, so I don't think the second line of the code is the problem.

My code is listed below:

$code = "\\example\example\John_Doe`'s_Folder\example.ps1"
invoke-expression -command $code

I have also tried wrapping the entire file path in double-quotes and single-quotes, but my program did not like that either. I can't remove the apostrophe as we have over a hundred of systems that are directing to John_Doe's_Folder.


Solution

  • Invoke-Expression should generally be avoided; definitely don't use it to invoke a script or external program.

    In your case, simply use &, the call operator to invoke your script via the path stored in variable $code (see this answer for background information), in which case the embedded ' needs no escaping at all:

    $code = "\\example\example\John_Doe's_Folder\example.ps1"
    & $code
    

    As for what you tried:

    "\\example\example\John_Doe`'s_Folder\example.ps1" turns into the following verbatim string content:

    \\example\example\John_Doe's_Folder\example.ps1
    

    That is, the ` was removed by PowerShell's parsing of the "..." string literal itself, inside of which ` acts as the escape character; since escape sequence `' has no special meaning, the ` is simply removed.

    For the ` to "survive", you need to escape the ` char. itself, which you can do with ``:

    "\\example\example\John_Doe``'s_Folder\example.ps1"