【问题标题】:writing double quotes to file name text with powershell使用powershell将双引号写入文件名文本
【发布时间】:2018-10-03 01:07:46
【问题描述】:

在为文件名文本添加双引号时,我一直很痛苦地发现我在哪里出错了。以下代码在 -whatif 保护伞下运行良好,但并非没有。

$a = "20`" board"
get-childitem | rename-item -newname {$_.fullname -replace "20 board", $a } -whatif

get-childitem | rename-item -newname {$_.fullname -replace "20 board","20`" board" } -whatif

期望的结果是将20 board 替换为20" board。 上面的 sn-ps 给我一个rename-item : Illegal characters in path. 错误。

【问题讨论】:

    标签: powershell filenames illegal-characters


    【解决方案1】:

    在 Windows 中,您不能在文件或文件夹名称中使用某些字符; 双引号就是其中之一。

    https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file了解更多信息。

    摘自该页面:

    The following reserved characters [are not allowed]:
    
    < (less than)
    (greater than)
    
    : (colon)
    " (double quote)
    / (forward slash)
    \ (backslash)
    | (vertical bar or pipe)
    ? (question mark)
    * (asterisk)
    

    【讨论】:

      【解决方案2】:

      ArcSet's helpful answer 包含关键指针:" 字符不能用于 Windows 上的文件和文件夹名称。

      所需功能有一个 - 次优 - 近似:您可以使用 non-ASCII 双引号,视觉上相似 em> - 但请注意,稍后您需要使用准确的引号来引用该文件(除非您使用通配符来匹配它),因此视觉上的相似性可能会导致混淆。

      'hi' > "20`“ board" # works, because “ is not a regular double quote
      

      Unicode character U+201C, the LEFT DOUBLE QUOTATION MARK

      请注意,PowerShell 将常规双引号和 视为可互换的,这就是为什么您仍需要在常规双引号字符串中使用 `-escape

      【讨论】: