问题描述
我正在使用Powershell.我的问题是我的文件路径(在本地计算机上不存在)中带有撇号.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.
当我执行第一行代码时,不会发生该错误,并且我甚至不需要反引号.我什至可以看到变量的内容与我正在使用的文件路径匹配.只有当我执行invoke-expression部分时,它才会给我错误.
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.
我正在使用 https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7 ,所以我认为代码就是问题所在.
I am using https://docs.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.
我的代码在下面列出:
$code = "\\example\example\John_Doe`'s_Folder\example.ps1"
invoke-expression -command $code
我也尝试将整个文件路径包装在双引号和单引号中,但是我的程序也不喜欢.我无法删除撇号,因为我们有100多个直接指向John_Doe's_Folder的系统.
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.
推荐答案
Invoke-Expression
通常应该避免;绝对不要使用它来调用脚本或外部程序.
在您的情况下,只需使用&
,呼叫操作符通过存储在变量 $ code
中的路径来调用脚本(请参见(了解背景信息),在这种情况下,嵌入式'
根本不需要转义:
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
关于您尝试过的事情:
"\\ example \ example \ John_Doe's_Folder \ example.ps1"
变成以下 verbatim 字符串内容:
"\\example\example\John_Doe`'s_Folder\example.ps1"
turns into the following verbatim string content:
\\example\example\John_Doe's_Folder\example.ps1
也就是说,通过PowerShell对"..."
字符串文字本身的解析,将`
删除了 ,其中的>`
充当转义符;由于转义序列`'
没有特殊含义,因此`
只是已删除.
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"
这篇关于如何使用Powershell在双引号中使用撇号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!