如何在PowerShell下的字符串中处理转义字符(`)

时间:2013-04-09 07:07:45

标签: string powershell escaping

我使用PowerShell从XML文件CDATA sectiona读取字符串,它包含PowerShell esacpe字符(`)作为字符串内容的一部分。当PowerShell正在读取和写入此内容时,它正在删除转义字符,这会导致使用相同内容时出现问题。

我无法在输入中添加像``这样的双转义序列,因为它是由用户提供的,我们不能限制用户使用它。

如何通过PowerShell正确处理?

1 个答案:

答案 0 :(得分:3)

我无法重现你的问题。需要更多信息。

的test.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<exampleOfACDATA>
<![CDATA[
    This is Graimer`s [CDATA[]] test.
    Notice that I just used a backtick in my text,
    which is PowerShell's escape character.
    I'm gonna store this in `$s` in PS.
]]>
</exampleOfACDATA>

Powershell的

PS > $xml = [xml](Get-Content .\Desktop\test.xml)
$s = $xml.exampleOfACDATA."#cdata-section"
$s

    This is Graimer`s [CDATA[]] test.
    Notice that I just used a backtick in my text,
    which is PowerShell's escape character.
    I'm gonna store this in `$s` in PS.

通常,为了确保特殊字符的行为与普通字符一样,变量不会扩展等,请在字符串周围使用单引号'text'。当你从其他来源(函数,文件......)中获取字符串时,这就是powershell的正常行为。

相关问题