透过命令提示符在powershell.exe中转义引号

13

在浏览这篇文章之后,我试图转义引号,但是在HTML引号中使用反斜杠不能转义右双引号,请注意它与普通的"不同。

例如:

正常工作:

powershell -noexit -command $str = \"hello '123' world\"; write-host $str

无法正常工作:

powershell -noexit -command $str = \"hello '123'” world\"; write-host $str

我该如何逃避这个问题?或者更好的方法是如何一次性逃避所有字符以摆脱这个麻烦!


你的“运行良好”的代码在命令提示符中无法正常工作。我收到了“字符串缺少终止符:“。””错误。但是,如果我从运行对话框中执行它,它可以正常处理。 - Robin
4个回答

14

使用反引号`来转义特殊的双引号,所以这样:

powershell -noexit -command $str = \"hello '123'” world\"; write-host $str
powershell -noexit -command $str = \"hello '123'`” world\"; write-host $str

编辑:

选项1:如果您更喜欢使用here-strings,您可以将上面的命令更改为powershell -file并运行您的powershell脚本文件。在那里尽可能多地使用here-strings。

选项2:如果您不想在调用/处理应用程序/脚本中处理特殊引号字符,您可以改为使用单引号。在这种情况下,您只需要通过加倍来转义单引号,像这样:

powershell -noexit -command $str = 'hello ''123''” world'; write-host $str

注意这里我没有对你的双引号字符做任何事情,它仍然可以正常工作。

因此,你的字符串替换代码可能会变得更易于阅读和维护,特别是如果编辑器无法正确显示此字符(例如PowerShell控制台 - 它显示正常的双引号)。


谢谢,但这不需要我知道右双引号在哪里吗?问题是我的 $str 是一个变量文本。它用于服务管理器(SCSM),只能通过命令提示符启动 PowerShell :(. $str 是一个描述字段,可能包含像上面那样的特殊字符,因此如果我可以转义所有内容,那就太好了。 - Morten_564834
@user2969412:谁/什么运行这个命令?它是一个C#应用程序吗?$str文本是如何传递进来的?在执行命令之前,您应该能够进行字符串替换,将"替换为\"`。 - Victor Zakharov
我们越来越接近了 :) - Morten_564834
@user2969412:我使用你提供的链接出现了以下错误信息:500 - 内部服务器错误。您正在查找的资源存在问题,无法显示。 - Victor Zakharov
这里运行良好。也许是华盛顿的温度下降了。这是另一个例子:http://blogs.technet.com/b/antoni/archive/2013/03/22/setting-status-using-powershell-and-converting-this-into-a-custom-task-in-service-manager-2012-sp1.aspx 请向下滚动查看截图。 - Morten_564834
显示剩余4条评论

5
  1. Start -command switch with ""
  2. Strings are recognized by surrounding a text with 4 times quotes at both sides: """" text """"

    Example:

    powershell.exe -command """""Recognized as string """""
    
    Output Stream:> Recognized as string
    
  3. For quotes in sub expressions double the quotes, that means 8 times quotes

    Example:

    powershell.exe -command """""""""How to quote in subexpression"""""""""
    
    Output Stream:> "How to quote in subexpression"
    

7
哇!8个双引号即16个单引号。命令提示符和PowerShell是完美搭配;) - maoizm

2

在命令提示符(或PowerShell)中运行以下命令:

powershell -noexit -command { $str = "hello '123' world"; write-host $str }

生成:
hello '123' world

这是否满足你的需求?

2
这并没有解决OP问题中智能引号字符的问题。是的,在某些屏幕上,很难区分该字符与普通双引号。在我的Surface 2上非常清晰,但在桌面上查看时,在问题中使用的比例字体中很难看到。 - Keith Hill
CTRL+++ ... 啊,我现在非常清楚地看到了。我相信答案现在在 Neolisk 下面 :) - Robin
1
运行得非常好! - pascalre

2

我遇到了同样的问题,并发现使用 Powershell 6.x (Core) 可以解决这个问题:

pwsh -command write-host "`u{22}quoted`u{22}" 

输出:

"quoted"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接