【问题标题】:What's the difference between single quote and double quote to define a string in powershell单引号和双引号在powershell中定义字符串有什么区别
【发布时间】:2011-05-11 16:14:47
【问题描述】:

一直困扰着我的简单问题:在 powershell 中,我可以像这样定义字符串:

$s1 = "Boogety boo"

$s2 = '.net rocks'

解释器有区别吗?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    双引号允许变量扩展,而单引号不允许:

    PS C:\Users\Administrator> $mycolor="red"
    PS C:\Users\Administrator> write-output -inputobject 'My favorite color is $mycolor'
    My favorite color is $mycolor
    

    来源:http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences

    (我知道1.0版本但原理还是一样)

    【讨论】:

    • onteria_所指的变量展开也称为“interpolation”。您也可以将插值视为“连接的特殊实例”,正如 Wikipedia 所提出的那样。
    • 另请参阅:Variable expansion in strings and here-strings,作者 Jeffrey Snover,其中更详细地介绍了将变量与字符串一起使用。
    • 一般来说,UNIX/Linux shell 的工作方式与引用相同。
    【解决方案2】:

    这并不是想成为一个更好的答案。只是另一种说法。

    撇号和引号之间的变量扩展与 UNIX shell(sh、ksh、bash)上的相同。使用撇号将按原样获取字符串,而不处理任何转义。

    PS C:\Users\lit> $x = "`t"
    PS C:\Users\lit> $x
    
    PS C:\Users\lit> Write-Output "now${x}is"
    now     is
    PS C:\Users\lit> $x = '`t'
    PS C:\Users\lit> $x
    `t
    PS C:\Users\lit> Write-Output "now${x}is"
    now`tis
    PS C:\Users\lit> $word = "easy"
    PS C:\Users\lit> "PowerShell is $word"
    PowerShell is easy
    PS C:\Users\lit> 'PowerShell is $word'
    PowerShell is $word
    

    【讨论】:

      【解决方案3】:

      这个问题在 PowerShell 文档的about_Quoting_Rules 文章中有直接的答案:

      双引号字符串

      用双引号括起来的字符串是一个可扩展的字符串。以美元符号 ($) 开头的变量名称在将字符串传递给命令进行处理之前替换为变量的值。

      例如:

      $i = 5
      "The value of $i is $i."
      

      这个命令的输出是:

      The value of 5 is 5.
      

      单引号字符串

      用单引号括起来的字符串是 逐字 字符串。字符串完全按照您键入的方式传递给命令。不执行替换。例如:

      $i = 5
      'The value of $i is $i.'
      

      这个命令的输出是:

      The value of $i is $i.
      

      【讨论】:

        猜你喜欢
        • 2011-03-27
        相关资源
        最近更新 更多